Kaki6876
Kaki6876

Reputation: 87

How can I emit subject when observable returns?

I want to refactor this to use observables:

    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;
  }

How can I emit the the isLoading$ observable right after the post returns, but not change the function return type?

Upvotes: 0

Views: 34

Answers (1)

ulmas
ulmas

Reputation: 2253

One way would be to do it in the pipe/tap:

  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;
  }

Another way would be in the subscription to your post() method:

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

Upvotes: 1

Related Questions