首页 > 解决方案 > “if”和“else if”条件都在过滤器函数中执行(Angular-8,JavaScript)

问题描述

“if”和“else if”条件都在过滤器函数中执行。当我尝试执行下面的程序时,我得到的输出为

在此处输入图像描述

 this.users.filter((hero)=> {
     if(hero.name === this.profileForm.value.name && hero.password === this.profileForm.value.password){
      this.router.navigate(['/dashboard']);
      console.log("in if")
     }else if(hero.name !== this.profileForm.value.name){
      console.log("in else if")
     this.isValid=false;
     }

任何人都可以帮助我代码有什么问题。

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl,Validators } from '@angular/forms';
import {
  CanActivate, Router,
  ActivatedRouteSnapshot,
  RouterStateSnapshot
}                           from '@angular/router';
@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {


  constructor(private router:Router) { }


  ngOnInit() {
  }
isValid:boolean=true;
  users =[{
    name:"user1",
    password:"password1"
  },
{
  name:"user2",
  password:"password2"
}
]

  profileForm = new FormGroup({
    name: new FormControl('',Validators.required),
    password: new FormControl('',[Validators.minLength(6),Validators.required]),
  });
  
onSubmit(){
  
  this.users.filter((hero)=> {
     if(hero.name === this.profileForm.value.name && hero.password === this.profileForm.value.password){
      this.router.navigate(['/dashboard']);
      console.log("in if")
     }else if(hero.name !== this.profileForm.value.name){
      console.log("in else if")
     this.isValid=false;
     }
    
  }); 
 
  
}

}
<div class="container">
    <div class="login-page">
        <h2 >Welcome to Timesheet Tracker</h2>
        <div class="form">
          
          <form class="login-form" [formGroup]="profileForm" (ngSubmit)="onSubmit()">
      
            <input type="text" placeholder="username"  formControlName="name"/>
            <span *ngIf="!profileForm.get('name').valid && profileForm.get('name').touched" class="help-block">Please enter user name..!</span>
            <input type="password" placeholder="password" formControlName="password"/>
            <span *ngIf="!profileForm.get('password').valid && profileForm.get('password').touched" class="help-block">Please enter valid password..!</span>
            <button type="submit" >login</button>
            
          </form>
          <p class="par" *ngIf="!isValid">Please enter valid user name and password..!</p>
        </div>
       
      </div>
</div>

标签: javascriptangular

解决方案


你不需要.filter这里。.filter迭代每个值。对于某些值,满足一个条件,对于另一些值,则满足另一个条件,因此两者if似乎else都被执行。

你需要做的是这样的:

 let heroFound = false;

  for(let hero of this.users){
   if(hero.name === this.profileForm.value.name && hero.password === 
  this.profileForm.value.password){
       heroFound = true;
       break;

    }

  }

  if(heroFound){
   this.router.navigate(['/dashboard']);
  }else{
    this.isValid=false;
  }

推荐阅读