view.html中的Angular HttpErrorResponse

时间:2018-05-13 20:08:40

标签: angular http status

我有一点问题,我不知道,当用户输入错误的密码时,如何在我的view.html中传递错误消息。

问题已解决

login.component.ts

export class LoginComponent implements OnInit {
   error : string;
   loginUserData = {}
   constructor(private auth: AuthService, private router: Router) { }
   ngOnInit() {
   }
   loginUser(){
      this.auth.loginUser(this.loginUserData).subscribe(
       res => {
         localStorage.setItem('token', res.token);
         this.router.navigate(['/special']);
       },
       err => {
           if( err instanceof HttpErrorResponse ) {
               if (err.status === 500) {
                   this.error = errLogin.error.message;
               }
           }
       }
       )
   }
}

login.component.html

    <div class="card-header">
      <h3 class="mb-0">Login</h3> {{ error }}
    </div>

1 个答案:

答案 0 :(得分:0)

声明变量名称错误

error : string;

然后分配像这样的值,

loginUser(){
      this.auth.loginUser(this.loginUserData).subscribe(
       res => {
         localStorage.setItem('token', res.token);
         this.router.navigate(['/special']);
       },
       err => {
           if( err instanceof HttpErrorResponse ) {
               if (err.status === 500) {
                   this.error = err.status
               }
           }
       }
       )
   }

并在组件中使用,

<div class="card-header">
      <h3 class="mb-0">Login</h3> {{ error }}
</div>