【问题标题】:Angular 6 - Observable never with throwAngular 6 - Observable 永远不会抛出
【发布时间】:2018-12-01 13:25:02
【问题描述】:

我正在寻找在 Angular 中处理 observable 的最佳方法。 目前的设计是:

public login(email: string, password: string): Observable<string> {
    return this.http
      .post(environment.apiUrl + '/login', {
        email: email,
        password: password
      })
      .map(response => {
        this.authenticationService.setToken(response["token"]);
        return "OK;"
      })
      .catch(error => {
        console.error('LoginService::error', error);
        return throwError(error);
      });
  }

这一切都很好,但我不想无缘无故地返回“OK”。

我尝试了以下方法,但它说您不能将 Observable 分配给 Observable

public login(email: string, password: string): Observable<never> {
    return this.http
      .post(environment.apiUrl + '/login', {
        email: email,
        password: password
      })
      .map(response => {
        this.authenticationService.setToken(response["token"]);
      })
      .catch(error => {
        console.error('LoginService::error', error);
        return throwError(error);
      });
  }

【问题讨论】:

  • 您正在寻找tap 运算符。

标签: angular rxjs observable angular6


【解决方案1】:
  public login(email: string, password: string) {
    return this.http
      .post(environment.apiUrl + '/login', {
        email: email,
        password: password
      }).pipe(
        tap({
          next: response => {
            this.authenticationService.setToken(response["token"]);
          }, 
          error: error => {
            console.error('LoginService::error', error);
          },
        }),
      )
  }

tap 运算符为您的 Observable 添加一些逻辑,用于每次发射和错误/完成事件(如果您愿意)。操作员不期望任何返回值并完全忽略它们,Observable 发生的所有其他事情都将照常进行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-16
    • 1970-01-01
    • 2018-11-30
    • 1970-01-01
    • 2019-01-15
    • 1970-01-01
    • 1970-01-01
    • 2013-10-16
    相关资源
    最近更新 更多