Requisition before executing another request in the angle

0

After the user is logged in to my application, all the requests that he / she performs must first hit an API that will validate if the plan agrees.

Is there any way to standardize the requisitions so that they always make this requisition and only then make the requested request if the plan is in agreement? Or do I need to place a requisition per requisition?

Would the Http injector do that?

Thank you

    
asked by anonymous 04.12.2018 / 16:56

1 answer

0

You need to use an HttpInterceptor.

For this you create a service of this kind:

@Injector()
export class RequestInterceptorService implements HttpInterceptor {

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        // adiciona o token desta forma
        // neste exemplo o token, quando existe, está guardado na localstorage
        if (localStorage.getItem('accessToken')) {
            request = request.clone({
                setHeaders: {
                    Authorization: 'Bearer ' + localStorage.getItem('accessToken')
                }
            });
        }


         return next.handle(request).pipe(
            tap(
              event => { },
              error => {
                this.handleErrors(error);
              }
            ),
            finalize(() => { })
        );
    }

    private handleErrors(err: HttpErrorResponse) {
        let errorMessage: string;
        if (err.status === 0) {
            errorMessage = 'Sem ligação à internet';
        } else if (err.status === 401) { // O token expirou ou nem foi enviado. Fazer novamente autenticação. 
            this.router.navigate(['/login']);
        } else { // ocorreu outro erro. Mostrar mensagem ao utilizador
            errorMessage = err.error.message;
        }

        if(errorMessage) {
            // mostrar mensagem em modal, por exemplo
        }
    }
}

And you add the service to the HTTP_INTERCEPTORS providers as follows:

@NgModule({
    declarations: [
        // ...
    ],
    imports: [
        // ...
    ],
    providers: [
        {
            provide: HTTP_INTERCEPTORS,
            useClass: RequestInterceptorService,
            multi: true,
        }
    ],
})

export class AppModule { }
    
04.12.2018 / 19:08