RxJS throwError事件未定向到处理程序?

时间:2018-12-11 02:28:20

标签: javascript node.js angular typescript rxjs

尝试build a login demo on stackblitz和IIUC时,login的第二个参数应该收到throwError的结果,但不是。任何想法:

  login(username: string, password:string) {
    this.authenticate(username, password).subscribe(
      user => {
        this.ostore.put(USER_KEY, user);
        this.ostore.put(AUTHENTICATION_ERROR_KEY, false);
        this.router.navigate(['/']);
      }),
      (error)=>{
        console.log("Storing the Error");
        error => this.ostore.put(AUTHENTICATION_ERROR_KEY, AUTHENTICATION_ERROR_MESSAGE);
      }
  }


  private authenticate(username:string, password:string) {
  // Mock Authentication Check
  if (username !== 'user') {
      return throwError(AUTHENTICATION_ERROR_MESSAGE);
  }
  return of({ name: username });
  }

1 个答案:

答案 0 :(得分:1)

接收错误的不是第二个参数,而是susbscribe的第二个回调。像这样进行“登录”:

login(username: string, password:string) {
  this.authenticate(username, password).subscribe(
    user => {
      this.ostore.put(USER_KEY, user);
      this.ostore.put(AUTHENTICATION_ERROR_KEY, false);
      this.router.navigate(['/']);
    },
    error => {
      console.log("Storing the Error");
      error => this.ostore.put(AUTHENTICATION_ERROR_KEY, AUTHENTICATION_ERROR_MESSAGE);
    })
}

在此处查看:https://stackblitz.com/edit/angular-material-login-logout-slice-demo-knrdjs?file=src/app/auth.service.ts