Using Router in services in Angular 4

后端 未结 1 997
深忆病人
深忆病人 2021-02-05 12:22

I\'ve been using Angular 2/4 for about a year now and I keep returning to this dilemma whether injecting Router into service can be considered as a bad practice?

This i

相关标签:
1条回答
  • 2021-02-05 12:40

    TL;DR: Its always better to do it from the component, since you can see where are the moving parts, wether in a service it can be done, but it is hard to identify as you will always check first the component.


    You can use Guards for that purpose and interceptors, i've added an error interceptor like the following, to route to logout when i get a 401:

    import { Injectable } from '@angular/core';
    import { HttpEvent, HttpErrorResponse, HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http';
    import { Router } from '@angular/router';
    import { Observable } from 'rxjs/Observable';
    import 'rxjs/add/observable/throw';
    import 'rxjs/add/operator/catch';
    
    @Injectable()
    export class ErrorInterceptor implements HttpInterceptor {
      constructor(private router: Router) {}
    
      intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(req).catch(
          (err: HttpErrorResponse) => {
            if (this.router.url !== '/login' && err.status === 401) {
              this.router.navigate(['/logout']);
            }
            return Observable.throw(err);
          }
        );
      }
    }
    

    Provide it in your app.module or in my case i've created a core.module for all the singletons to keep clean my app.module

    {
      provide: HTTP_INTERCEPTORS,
      useClass: ErrorInterceptor,
      multi: true
    }
    

    With something like this you don't have to put routing in a service, you will get a 401 from your api when token is invalid.

    You might have to work out a bit this code, tried to be as generic as possible.

    0 讨论(0)
提交回复
热议问题