yevhensh
yevhensh

Reputation: 410

Angular 2 rxJs, subscribe error

I have method in some service:

public approveTokenExpiration(): Observable<any> {
    let header = new Headers();
    header.append('Authorization', this.getTokenHeaderValue());
    let options = new RequestOptions({headers: header});
    return this.http.get(Constants.oauthLoginEndPointUrl, options)
      .map(res => {
        return res;
      })
      .catch(err => {
        return refreshToken()
          .subscribe(res => {
            return res;
          });
      });
  }

refresh token method:

public refreshToken(): Observable<any> {
    let refreshToken = localStorage.getItem(Constants.REFRESH_TOKEN);
    let refreshEndPointUrl = Constants.oauthLoginEndPointUrl + "?grant_type=refresh_token&client_id=" +
      Constants.clientId + "&client_secret=" + Constants.clientSecret + "&refresh_token=" + refreshToken;
    this.http
      .post(refreshEndPointUrl, {})
      .map(res => {
        this.setAuthLocalStorageItems(res);
        this.removeAuthLocalStorageItems();
        return res;
      });
  }

And subscription:

request(url: string|Request, options?: RequestOptionsArgs): Observable<Response> {
    this.customOptions = options;
    return this.authService.approveTokenExpiration()
      .subscribe(
        res => {
          this.addAuthHeader();
          return super.request(url, this.customOptions);
        },
        err => {
          this.authService.refreshToken();
          this.addAuthHeader();
          return super.request(url, this.customOptions);
        });
  }

I'm getting following error:

ERROR in [at-loader] ./src/app/auth/intercept/auth.interceptor.ts:18:5 TS2322: Type 'Subscription' is not assignable to type 'Observable'. Property '_isScalar' is missing in type 'Subscription'.

And check pls if everything is okay with my RxJs handling;

Upvotes: 0

Views: 454

Answers (1)

BeetleJuice
BeetleJuice

Reputation: 40886

There are a couple of problems with your code. The specific problem you raised is caused by this part:

request(url: string|Request, options?: RequestOptionsArgs): Observable<Response> {
    this.customOptions = options;
    return this.authService.approveTokenExpiration()
      .subscribe(... // <- this will return a Subscription

Notice that you define the request function to return a result of type Observable<Response>. However, your return statement is returning ...subscribe(), which is a Subscription. If you want to return an observable, don't call .subscribe(). Just return what you get from approveTokenExpiration()

You're on the right track. The request function should return an Observable. It is the calling code (your component) that should call .subscribe() on that Observable because it is at that point the request will be triggered.

Upvotes: 1

Related Questions