【问题标题】:How can I emit subject when observable returns?当可观察返回时,我如何发出主题?
【发布时间】:2020-12-04 20:35:56
【问题描述】:

我想重构它以使用可观察对象:

    post<T>(
    url: string,
    body: any,
    params?: HttpParams,
    headers?: HttpHeaders
  ): Observable<T> {
    this.isLoading$.next(true);
    const res = this.http
      .post<T>(url, body, { headers, params })
      .pipe(timeout(3000));
    this.isLoading$.next(false);
    return res;
  }

如何在帖子返回后立即发出 isLoading$ observable,但不更改函数返回类型?

【问题讨论】:

    标签: angular rxjs observable rxjs-observables


    【解决方案1】:

    一种方法是在管道/水龙头中进行:

      post<T>(
        url: string,
        body: any,
        params?: HttpParams,
        headers?: HttpHeaders
      ): Observable<T> {
        this.isLoading$.next(true);
        const res = this.http
          .post<T>(url, body, { headers, params })
          .pipe(
            timeout(3000),
            tap(_ => { this.isLoading$.next(false); }
          );
        return res;
      }
    

    另一种方式是订阅您的post() 方法:

    post(url, body, params, headers).subscribe(_ => { this.isLoading$.next(false); })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-23
      • 2018-12-16
      • 1970-01-01
      • 2019-02-18
      相关资源
      最近更新 更多