Angular - Set headers for every request

前端 未结 19 1646
[愿得一人]
[愿得一人] 2020-11-22 07:43

I need to set some Authorization headers after the user has logged in, for every subsequent request.


To set headers for a particular request,



        
19条回答
  •  长发绾君心
    2020-11-22 08:35

    You can use canActive in your routes, like so:

    import { Injectable } from '@angular/core';
    import { Router } from '@angular/router';
    import { CanActivate } from '@angular/router';
    import { AuthService } from './auth.service';
    
    @Injectable()
    export class AuthGuard implements CanActivate {
    
      constructor(private auth: AuthService, private router: Router) {}
    
      canActivate() {
        // If user is not logged in we'll send them to the homepage 
        if (!this.auth.loggedIn()) {
          this.router.navigate(['']);
          return false;
        }
        return true;
      }
    
    }
    
    const appRoutes: Routes = [
      {
        path: '', redirectTo: '/deals', pathMatch: 'full'
      },
      {
        path: 'special',
        component: PrivateDealsComponent,
        /* We'll use the canActivate API and pass in our AuthGuard.
           Now any time the /special route is hit, the AuthGuard will run
           first to make sure the user is logged in before activating and
           loading this route. */
        canActivate: [AuthGuard]
      }
    ];
    

    Taken from: https://auth0.com/blog/angular-2-authentication

提交回复
热议问题