Home > Software engineering >  Angular subscription is not assignable to observable
Angular subscription is not assignable to observable

Time:12-08

I need help creating a function that gets the categories from my API and also checks for status of the call. I have written my function like the code bellow but it keep showing me the bellow error:

Argument of type '(token: GetResult) => Subscription' is not assignable to parameter of type '(value: GetResult, index: number) => ObservableInput<any>'

Here is the code of my function:

getCategories() {
  return from(Preferences.get({ key: "TOKEN_KEY" })).pipe(
    switchMap((token) => {
      const headers = new HttpHeaders().set(
        "Authorization",
        `Bearer ${token.value}`
      );
      return this.httpClient
        .get(`${environment.apiUrl}categories`, {
          headers,
          observe: "response",
        })
        .subscribe(
          (res) => {
            return res.body;
          },
          (error) => {
            console.log(error.status);
            if (error.status === 400) {
              console.log(error.error.message);
            }
            if (error.status === 401) {
              this.authService.logout();
              this.router.navigateByUrl("/login", { replaceUrl: true });
            }
          }
        );
    })
  );
}

CodePudding user response:

You should not use .subscribe inside a subscription. .subscribe returns a Subscription which can't be assigned to the Observable that a switchMap should return.

Use catchError to to handle the error case and a map to handle the success case.

getCategories() {
  return from(Preferences.get({ key: 'TOKEN_KEY' })).pipe(
    switchMap(token => {
      const headers = new HttpHeaders().set('Authorization', `Bearer ${token.value}`);
      return this.httpClient.get(
        `${environment.apiUrl}categories`, 
        { headers, observe: 'response' }
      )
    }),
    catchError(error => {
      console.log(error.status);
      if (error.status === 400) {
        console.log(error.error.message);
      }
      if (error.status === 401) {
        this.authService.logout();
        this.router.navigateByUrl('/login', { replaceUrl: true });
      }

      return EMPTY
    }),
    map(res => res.body)
  )
};
  • Related