错误TypeError:无法读取未定义的属性“用户名”在我的浏览器控制台中列出

时间:2019-11-28 00:58:55

标签: javascript html angular typescript web-applications

我目前正在尝试使用Angular 8将登录页面路由到另一个页面,但这在我的浏览器控制台中给了我这个错误。 错误TypeError:无法读取未定义的属性“用户名”     在LoginComponent.push ../ src / app / login / login.component.ts.LoginComponent.login(login.component.ts:30)

HTML代码:

<div class="login-grid">
  <div></div>
  <form class="login-form box-shadow">
    <div class="form-group">
      <label  for="exampleInputEmail1">User Name</label>
      <input [(ngModel)]="user.username" name="username" type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="User Name">
    </div>
    <div  class="form-group">
      <label  for="exampleInputPassword1">Password</label>
      <input [(ngModel)]="user.password" name="password"  type="password" class="form-control" id="exampleInputPassword1" placeholder="Password">
    </div>
    <div class="form-group form-check">
      <input type="checkbox" class="form-check-input" id="exampleCheck1">
      <label class="form-check-label" for="exampleCheck1">Remember Me?</label>
    </div>
    <button mat-raised-button color="primary" (click)="login(creds)">Login</button>
  </form>
  <div></div>
</div>

打字稿代码:

export interface IUser {
  id?: number;
  username: string;
  password: string;
}
@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  user: IUser = { username: null, password: null };

  constructor(private router: Router, private toastService: ToastService) {

  }

  ngOnInit() {

  }
  login(user: IUser) {
    console.log('this user is ', user);
    const presetUser = { username: 'admin', password: 'password' };

    if (user.username != null && user.password != null &&
      user.username !== '' && user.password !== '') {
      // log the user in
      console.log('from within if statement...');
      this.router.navigate(['contacts', user]);
      if (user.username === presetUser.username &&
        user.password === presetUser.password) {
        // log the user into contacts page
        // saving data to localStorage
        localStorage.setItem('user', JSON.stringify(user));
        // navigate to contacts page
        this.router.navigate(['contacts', user]);
      } else {
        this.toastService.showToast('warning', 2000, 'Username or password is wrong!');
      }

    } else {
      console.log('Must specify credentials');
      this.toastService.showToast('danger', 2000, 'Must specify credentials');
    }
  }
}

1 个答案:

答案 0 :(得分:0)

用户是未定义的,因为在提交表单时,您将拥有以下内容:

 <button mat-raised-button color="primary" (click)="login(creds)">Login</button>

但是creds不是什么,所以您会得到未定义的错误。 您已经在代码文件中将用户定义为变量,因此可以正常工作:

login() {
    console.log('user', this.user);
}

This.user是链接到html中ngModels的东西。