How to get status code in angular observable

Discussão em 'Angular' iniciado por mafortis, Novembro 17, 2024.

  1. mafortis

    mafortis Guest

    I have services below that I'd like to get status code and handle if statements in it but so far I couldn't figure it out

    import { Injectable } from '@angular/core';
    import { EnvService } from './env.service';
    import { tap } from 'rxjs/operators';
    import { Observable, from } from 'rxjs';
    import { map, switchMap } from 'rxjs/operators';
    import { HttpClient, HttpHeaders } from '@angular/common/http';
    import { NativeStorage } from '@ionic-native/native-storage/ngx';
    import { Plugins } from '@capacitor/core';
    const { Storage } = Plugins;

    @Injectable({
    providedIn: 'root'
    })
    export class InvoicesServiceService {

    token: any;

    constructor(
    private env: EnvService,
    private http: HttpClient,
    private nativeStorage: NativeStorage
    ) {
    Storage.get({ key: 'token' }).then((token: any) => {
    this.token = JSON.parse(token.value)
    }).catch(error => console.error(error));
    }

    // All
    getInvoices(): Observable<any> {
    const tokenPromise =
    this.token === undefined
    ? Storage.get({ key: 'token' })
    : Promise.resolve(this.token);

    return from(tokenPromise).pipe(
    switchMap((token) => {
    this.token = this.token;
    const httpOptions = {
    headers: new HttpHeaders({
    Accept: 'application/json, text/plain',
    'Content-Type': 'application/json',
    Authorization: this.token.access_token,
    }),
    };
    return this.http
    .get(`${this.env.Dashboard}` + '/invoices', httpOptions)
    .pipe(map((data) => data));
    })
    );
    }


    What I try to do is that if, status code is 403 redirect user to specific route other than that just return data.

    any idea?

    Continue reading...

Compartilhe esta Página