【问题标题】:RxJS throwError event not directed to handler?RxJS throwError 事件未定向到处理程序?
【发布时间】:2019-05-11 23:50:24
【问题描述】:

尝试 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 });
  }

【问题讨论】:

    标签: javascript node.js angular typescript rxjs


    【解决方案1】:

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

    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

    【讨论】:

    • 太棒了 - 刚刚意识到我放错了第一个括号 - 谢谢!
    • @Ole:哈哈,确实发生了!
    猜你喜欢
    • 1970-01-01
    • 2021-08-19
    • 2017-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-29
    • 2020-01-27
    • 2016-05-26
    相关资源
    最近更新 更多