Angular - 为每个请求设置标头

时间:2015-12-25 15:33:04

标签: angular

我需要在用户登录后为每个后续请求设置一些授权标头。

为特定请求设置标头

import {Headers} from 'angular2/http';
var headers = new Headers();
headers.append(headerName, value);

// HTTP POST using these headers
this.http.post(url, data, {
  headers: headers
})
// do something with the response

Reference

但是以这种方式为每个请求手动设置请求标头是不可行的。

如何在用户登录后设置标头集,并在注销时删除这些标头?

21 个答案:

答案 0 :(得分:348)

要回答,您提出质疑,您可以提供从Angular包装原始Http对象的服务。如下所述。

import {Injectable} from '@angular/core';
import {Http, Headers} from '@angular/http';

@Injectable()
export class HttpClient {

  constructor(private http: Http) {}

  createAuthorizationHeader(headers: Headers) {
    headers.append('Authorization', 'Basic ' +
      btoa('username:password')); 
  }

  get(url) {
    let headers = new Headers();
    this.createAuthorizationHeader(headers);
    return this.http.get(url, {
      headers: headers
    });
  }

  post(url, data) {
    let headers = new Headers();
    this.createAuthorizationHeader(headers);
    return this.http.post(url, data, {
      headers: headers
    });
  }
}

而不是注入Http对象,你可以注入这个(HttpClient)。

import { HttpClient } from './http-client';

export class MyComponent {
  // Notice we inject "our" HttpClient here, naming it Http so it's easier
  constructor(http: HttpClient) {
    this.http = httpClient;
  }

  handleSomething() {
    this.http.post(url, data).subscribe(result => {
        // console.log( result );
    });
  }
}

我还认为可以使用Http类的多个提供程序来完成某些操作,方法是提供自己的类Http扩展...查看此链接:http://blog.thoughtram.io/angular2/2015/11/23/multi-providers-in-angular-2.html

答案 1 :(得分:104)

HTTP拦截器now available来自@angular/common/http的新HttpClient从Angular 4.3.x及更高版本

现在为每个请求添加标题非常简单:

import {
  HttpEvent,
  HttpInterceptor,
  HttpHandler,
  HttpRequest,
} from '@angular/common/http';

export class AddHeaderInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    // Clone the request to add the new header
    const clonedRequest = req.clone({ headers: req.headers.set('Authorization', 'Bearer 123') });

    // Pass the cloned request instead of the original request to the next handle
    return next.handle(clonedRequest);
  }
}

有一个principle of immutability,这就是在设置新内容之前需要克隆请求的原因。

由于编辑标题是一项非常常见的任务,实际上有一个快捷方式(克隆请求时):

const clonedRequest = req.clone({ setHeaders: { Authorization: 'Bearer 123' } });

创建拦截器后,您应该使用HTTP_INTERCEPTORS提供注册。

import { HTTP_INTERCEPTORS } from '@angular/common/http';

@NgModule({
  providers: [{
    provide: HTTP_INTERCEPTORS,
    useClass: AddHeaderInterceptor,
    multi: true,
  }],
})
export class AppModule {}

答案 2 :(得分:76)

在这种情况下,扩展BaseRequestOptions可能会有很大帮助。请查看以下代码:

import {provide} from 'angular2/core';
import {bootstrap} from 'angular2/platform/browser';
import {HTTP_PROVIDERS, Headers, Http, BaseRequestOptions} from 'angular2/http';

import {AppCmp} from './components/app/app';


class MyRequestOptions extends BaseRequestOptions {
  constructor () {
    super();
    this.headers.append('My-Custom-Header','MyCustomHeaderValue');
  }
} 

bootstrap(AppCmp, [
  ROUTER_PROVIDERS,
  HTTP_PROVIDERS,
  provide(RequestOptions, { useClass: MyRequestOptions })
]);

这应该包括“我的自定义标题”&#39;在每次通话中。

<强>更新

为了能够随时更改标题而不是上面的代码,您还可以使用以下代码添加新标题:

this.http._defaultOptions.headers.append('Authorization', 'token');

删除你可以做

this.http._defaultOptions.headers.delete('Authorization');

还有另一个功能可用于设置值:

this.http._defaultOptions.headers.set('Authorization', 'token');

上述解决方案在打字稿上下文中仍然不完全有效。 _defaultHeaders受到保护,不应该像这样使用。我建议使用上面的解决方案进行快速修复,但从长远来看,最好在http调用周围编写自己的包装器,它也会处理auth。从auth0中获取以下示例,该示例更好,更干净。

here

更新 - 2018年6月 我看到很多人都在寻求这个解决方案,但我会建议不这样做。全局追加标头会将身份验证令牌发送到从您的应用发出的每个 API呼叫。因此api调用第三方插件如内部通信或zendesk或任何其他api也将带有您的授权标头。这可能会导致严重的安全漏洞。 因此,请在全局范围内使用拦截器,但要手动检查传出呼叫是否指向服务器的api端点,然后附加auth标头。

答案 3 :(得分:24)

虽然我很晚才回答,但它可能对其他人有所帮助。要在使用@NgModule时为所有请求注入标头,可以执行以下操作:

(我在Angular 2.0.1中进行了测试)

/**
 * Extending BaseRequestOptions to inject common headers to all requests.
 */
class CustomRequestOptions extends BaseRequestOptions {
    constructor() {
        super();
        this.headers.append('Authorization', 'my-token');
        this.headers.append('foo', 'bar');
    }
}

现在在@NgModule执行以下操作:

@NgModule({
    declarations: [FooComponent],
    imports     : [

        // Angular modules
        BrowserModule,
        HttpModule,         // This is required

        /* other modules */
    ],
    providers   : [
        {provide: LocationStrategy, useClass: HashLocationStrategy},
        // This is the main part. We are telling Angular to provide an instance of
        // CustomRequestOptions whenever someone injects RequestOptions
        {provide: RequestOptions, useClass: CustomRequestOptions}
    ],
    bootstrap   : [AppComponent]
})

答案 4 :(得分:15)

Angular 2.1.2我通过扩展角度Http来接近这个:

import {Injectable} from "@angular/core";
import {Http, Headers, RequestOptionsArgs, Request, Response, ConnectionBackend, RequestOptions} from "@angular/http";
import {Observable} from 'rxjs/Observable';

@Injectable()
export class HttpClient extends Http {

  constructor(protected _backend: ConnectionBackend, protected _defaultOptions: RequestOptions) {

    super(_backend, _defaultOptions);
  }

  _setCustomHeaders(options?: RequestOptionsArgs):RequestOptionsArgs{
    if(!options) {
      options = new RequestOptions({});
    }
    if(localStorage.getItem("id_token")) {

      if (!options.headers) {

        options.headers = new Headers();


      }
      options.headers.set("Authorization", localStorage.getItem("id_token"))
    }
    return options;
  }


  request(url: string|Request, options?: RequestOptionsArgs): Observable<Response> {
    options = this._setCustomHeaders(options);
    return super.request(url, options)
  }
}

然后在我的应用程序提供商中,我能够使用自定义工厂来提供&#39; Http&#39;

import { RequestOptions, Http, XHRBackend} from '@angular/http';
import {HttpClient} from './httpClient';
import { RequestOptions, Http, XHRBackend} from '@angular/http';
import {HttpClient} from './httpClient';//above snippet

function httpClientFactory(xhrBackend: XHRBackend, requestOptions: RequestOptions): Http {
  return new HttpClient(xhrBackend, requestOptions);
}

@NgModule({
  imports:[
    FormsModule,
    BrowserModule,
  ],
  declarations: APP_DECLARATIONS,
  bootstrap:[AppComponent],
  providers:[
     { provide: Http, useFactory: httpClientFactory, deps: [XHRBackend, RequestOptions]}
  ],
})
export class AppModule {
  constructor(){

  }
}

现在我不需要声明每个Http方法,并且可以在我的应用程序中正常使用http

答案 5 :(得分:12)

通过扩展Angular 2 Http提供程序来创建自定义Http类,并简单地覆盖自定义Http类中的constructorrequest方法。以下示例在每个http请求中添加Authorization标头。

import {Injectable} from '@angular/core';
import {Http, XHRBackend, RequestOptions, Request, RequestOptionsArgs, Response, Headers} from '@angular/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';

@Injectable()
export class HttpService extends Http {

  constructor (backend: XHRBackend, options: RequestOptions) {
    let token = localStorage.getItem('auth_token'); // your custom token getter function here
    options.headers.set('Authorization', `Bearer ${token}`);
    super(backend, options);
  }

  request(url: string|Request, options?: RequestOptionsArgs): Observable<Response> {
    let token = localStorage.getItem('auth_token');
    if (typeof url === 'string') { // meaning we have to add the token to the options, not in url
      if (!options) {
        // let's make option object
        options = {headers: new Headers()};
      }
      options.headers.set('Authorization', `Bearer ${token}`);
    } else {
    // we have to add the token to the url object
      url.headers.set('Authorization', `Bearer ${token}`);
    }
    return super.request(url, options).catch(this.catchAuthError(this));
  }

  private catchAuthError (self: HttpService) {
    // we have to pass HttpService's own instance here as `self`
    return (res: Response) => {
      console.log(res);
      if (res.status === 401 || res.status === 403) {
        // if not authenticated
        console.log(res);
      }
      return Observable.throw(res);
    };
  }
}

然后配置您的主app.module.ts,将XHRBackend作为ConnectionBackend提供商,将RequestOptions提供给您的自定义Http类:

import { HttpModule, RequestOptions, XHRBackend } from '@angular/http';
import { HttpService } from './services/http.service';
...
@NgModule({
  imports: [..],
  providers: [
    {
      provide: HttpService,
      useFactory: (backend: XHRBackend, options: RequestOptions) => {
        return new HttpService(backend, options);
      },
      deps: [XHRBackend, RequestOptions]
    }
  ],
  bootstrap: [ AppComponent ]
})

之后,您现在可以在服务中使用自定义http提供程序。例如:

import { Injectable }     from '@angular/core';
import {HttpService} from './http.service';

@Injectable()
class UserService {
  constructor (private http: HttpService) {}

  // token will added automatically to get request header
  getUser (id: number) {
    return this.http.get(`/users/${id}`).map((res) => {
      return res.json();
    } );
  }
}

这是一份全面的指南 - http://adonespitogo.com/articles/angular-2-extending-http-provider/

答案 6 :(得分:8)

迟到总比没有...... =)

您可以采用扩展BaseRequestOptions的概念(从此处https://angular.io/docs/ts/latest/guide/server-communication.html#!#override-default-request-options)并“动态”刷新标题(不仅仅是在构造函数中)。您可以使用getter / setter“headers”属性覆盖,如下所示:

import { Injectable } from '@angular/core';
import { BaseRequestOptions, RequestOptions, Headers } from '@angular/http';

@Injectable()
export class DefaultRequestOptions extends BaseRequestOptions {

    private superHeaders: Headers;

    get headers() {
        // Set the default 'Content-Type' header
        this.superHeaders.set('Content-Type', 'application/json');

        const token = localStorage.getItem('authToken');
        if(token) {
            this.superHeaders.set('Authorization', `Bearer ${token}`);
        } else {
            this.superHeaders.delete('Authorization');
        }
        return this.superHeaders;
    }

    set headers(headers: Headers) {
        this.superHeaders = headers;
    }

    constructor() {
        super();
    }
}

export const requestOptionsProvider = { provide: RequestOptions, useClass: DefaultRequestOptions };

答案 7 :(得分:7)

对于Angular 5及更高版本,我们可以使用HttpInterceptor来概括请求和响应操作。 这有助于我们避免重复:

1)通用标头

2)指定响应类型

3)查询请求

import { Injectable } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor,
  HttpResponse,
  HttpErrorResponse
} from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/do';

@Injectable()
export class AuthHttpInterceptor implements HttpInterceptor {

  requestCounter: number = 0;
  constructor() {
  }

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

    request = request.clone({
      responseType: 'json',
      setHeaders: {
        Authorization: `Bearer token_value`,
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
      }
    });

    return next.handle(request).do((event: HttpEvent<any>) => {
      if (event instanceof HttpResponse) {
        // do stuff with response if you want
      }
    }, (err: any) => {
      if (err instanceof HttpErrorResponse) {
        // do stuff with response error if you want
      }
    });
  }
}

我们可以使用AuthHttpInterceptor类作为HttpInterceptors的提供程序:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app.routing-module';
import { AuthHttpInterceptor } from './services/auth-http.interceptor';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule,
    BrowserAnimationsModule,
  ],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: AuthHttpInterceptor,
      multi: true
    }
  ],
  exports: [],
  bootstrap: [AppComponent]
})
export class AppModule {
}

答案 8 :(得分:6)

以下是已接受答案的改进版本,已针对Angular2 final更新:

import {Injectable} from "@angular/core";
import {Http, Headers, Response, Request, BaseRequestOptions, RequestMethod} from "@angular/http";
import {I18nService} from "../lang-picker/i18n.service";
import {Observable} from "rxjs";
@Injectable()
export class HttpClient {

    constructor(private http: Http, private i18n: I18nService ) {}

    get(url:string):Observable<Response> {
        return this.request(url, RequestMethod.Get);
    }

    post(url:string, body:any) {   
        return this.request(url, RequestMethod.Post, body);
    }

    private request(url:string, method:RequestMethod, body?:any):Observable<Response>{

        let headers = new Headers();
        this.createAcceptLanguageHeader(headers);

        let options = new BaseRequestOptions();
        options.headers = headers;
        options.url = url;
        options.method = method;
        options.body = body;
        options.withCredentials = true;

        let request = new Request(options);

        return this.http.request(request);
    }

    // set the accept-language header using the value from i18n service that holds the language currently selected by the user
    private createAcceptLanguageHeader(headers:Headers) {

        headers.append('Accept-Language', this.i18n.getCurrentLang());
    }
}

当然,如果需要,我应该对deleteput等方法进行扩展(我的项目目前还不需要它们)。

优点是get / post / ...方法中的重复代码较少。

请注意,在我的情况下,我使用cookie进行身份验证。我需要i18​​n的标头(Accept-Language标头),因为我们的API返回的许多值都是用用户的语言翻译的。在我的应用程序中,i18n服务保留用户当前选择的语言。

答案 9 :(得分:5)

虽然我很晚才回答这个问题,但是如果有人正在寻求更简单的解决方案。

我们可以使用angular2-jwt。在从Angular 2应用程序发出HTTP请求时,angular2-jwt可自动将JSON Web令牌(JWT)作为授权标头附加。

我们可以使用高级配置选项设置全局标题

export function authHttpServiceFactory(http: Http, options: RequestOptions) {
  return new AuthHttp(new AuthConfig({
    tokenName: 'token',
        tokenGetter: (() => sessionStorage.getItem('token')),
        globalHeaders: [{'Content-Type':'application/json'}],
    }), http, options);
}

并按照

发送每个请求令牌
    getThing() {
  let myHeader = new Headers();
  myHeader.append('Content-Type', 'application/json');

  this.authHttp.get('http://example.com/api/thing', { headers: myHeader })
    .subscribe(
      data => this.thing = data,
      err => console.log(error),
      () => console.log('Request Complete')
    );

  // Pass it after the body in a POST request
  this.authHttp.post('http://example.com/api/thing', 'post body', { headers: myHeader })
    .subscribe(
      data => this.thing = data,
      err => console.log(error),
      () => console.log('Request Complete')
    );
}

答案 10 :(得分:5)

这就是我为每个请求设置令牌的方法。

import { RequestOptions, BaseRequestOptions, RequestOptionsArgs } from '@angular/http';

export class CustomRequestOptions extends BaseRequestOptions {

    constructor() {
        super();
        this.headers.set('Content-Type', 'application/json');
    }
    merge(options?: RequestOptionsArgs): RequestOptions {
        const token = localStorage.getItem('token');
        const newOptions = super.merge(options);
        if (token) {
            newOptions.headers.set('Authorization', `Bearer ${token}`);
        }

        return newOptions;
    }
}

在app.module.ts中注册

@NgModule({
    declarations: [
        AppComponent
    ],
    imports: [
        BrowserModule
    ],
    providers: [
        { provide: RequestOptions, useClass: CustomRequestOptions }
    ],
    bootstrap: [AppComponent]
})
export class AppModule { }

答案 11 :(得分:5)

经过一番调查后,我发现最后也是最简单的方法是扩展我喜欢的BaseRequestOptions 以下是我因某种原因尝试和放弃的方式:
1.扩展BaseRequestOptions,并在constructor()中添加动态标头。如果我登录,它无法工作。它将被创建一次。所以它不是动态的 2.延长Http。与上述原因相同,我无法在constructor()中添加动态标头。如果我重写request(..)方法,并设置标题,如下所示:

request(url: string|Request, options?: RequestOptionsArgs): Observable<Response> {
 let token = localStorage.getItem(AppConstants.tokenName);
 if (typeof url === 'string') { // meaning we have to add the token to the options, not in url
  if (!options) {
    options = new RequestOptions({});
  }
  options.headers.set('Authorization', 'token_value');
 } else {
  url.headers.set('Authorization', 'token_value');
 }
 return super.request(url, options).catch(this.catchAuthError(this));
}

您只需要覆盖此方法,但不要覆盖每个get / post / put方法。

3.我首选的解决方案是扩展BaseRequestOptions并覆盖merge()

@Injectable()
export class AuthRequestOptions extends BaseRequestOptions {

 merge(options?: RequestOptionsArgs): RequestOptions {
  var newOptions = super.merge(options);
  let token = localStorage.getItem(AppConstants.tokenName);
  newOptions.headers.set(AppConstants.authHeaderName, token);
  return newOptions;
 }
}

将为每个请求调用此merge()函数。

答案 12 :(得分:5)

如何保持单独的服务如下

include DeviseTokenAuth::Concerns::User

当您从其他地方拨打此电话时,请使用 import {Injectable} from '@angular/core'; import {Headers, Http, RequestOptions} from '@angular/http'; @Injectable() export class HttpClientService extends RequestOptions { constructor(private requestOptionArgs:RequestOptions) { super(); } addHeader(headerName: string, headerValue: string ){ (this.requestOptionArgs.headers as Headers).set(headerName, headerValue); } }

您将看到添加的标题,例如: - 授权,如下所示

enter image description here

答案 13 :(得分:4)

我喜欢覆盖默认选项的想法,这似乎是一个很好的解决方案。

但是,如果您要扩展Http课程。请务必通读!

这里的一些答案实际上显示了request()方法的错误重载,这可能导致难以捕获的错误和奇怪的行为。我自己偶然发现了这一点。

此解决方案基于Angular request()中的4.2.x方法实现,但应该是未来兼容的:

import {Observable} from 'rxjs/Observable';
import {Injectable} from '@angular/core';

import {
  ConnectionBackend, Headers,
  Http as NgHttp,
  Request,
  RequestOptions,
  RequestOptionsArgs,
  Response,
  XHRBackend
} from '@angular/http';


import {AuthenticationStateService} from '../authentication/authentication-state.service';


@Injectable()
export class Http extends NgHttp {

  constructor (
    backend: ConnectionBackend,
    defaultOptions: RequestOptions,
    private authenticationStateService: AuthenticationStateService
  ) {
    super(backend, defaultOptions);
  }


  request (url: string | Request, options?: RequestOptionsArgs): Observable<Response> {

    if ('string' === typeof url) {

      url = this.rewriteUrl(url);
      options = (options || new RequestOptions());
      options.headers = this.updateHeaders(options.headers);

      return super.request(url, options);

    } else if (url instanceof Request) {

      const request = url;
      request.url = this.rewriteUrl(request.url);
      request.headers = this.updateHeaders(request.headers);

      return super.request(request);

    } else {
      throw new Error('First argument must be a url string or Request instance');
    }

  }


  private rewriteUrl (url: string) {
    return environment.backendBaseUrl + url;
  }

  private updateHeaders (headers?: Headers) {

    headers = headers || new Headers();

    // Authenticating the request.
    if (this.authenticationStateService.isAuthenticated() && !headers.has('Authorization')) {
      headers.append('Authorization', 'Bearer ' + this.authenticationStateService.getToken());
    }

    return headers;

  }

}

请注意,我正在以import { Http as NgHttp } from '@angular/http';方式导入原始类,以防止名称冲突。

  

此处解决的问题是request()方法有两个不同的呼叫签名。传递Request对象而不是URL string时,Angular会忽略options参数。因此,必须妥善处理这两种情况。

以下是如何使用DI容器注册此重写类的示例:

export const httpProvider = {
  provide: NgHttp,
  useFactory: httpFactory,
  deps: [XHRBackend, RequestOptions, AuthenticationStateService]
};


export function httpFactory (
  xhrBackend: XHRBackend,
  requestOptions: RequestOptions,
  authenticationStateService: AuthenticationStateService
): Http {
  return new Http(
    xhrBackend,
    requestOptions,
    authenticationStateService
  );
}

使用这种方法你可以正常注入Http类,但是你的被覆盖的类将被神奇地注入。这使您可以轻松集成解决方案,而无需更改应用程序的其他部分(操作中的多态)。

只需将httpProvider添加到模块元数据的providers属性中即可。

答案 14 :(得分:1)

最简单的

创建config.ts文件

import { HttpHeaders } from '@angular/common/http';

export class Config {
    url: string = 'http://localhost:3000';
    httpOptions: any = {
        headers: new HttpHeaders({
           'Content-Type': 'application/json',
           'Authorization': JSON.parse(localStorage.getItem('currentUser')).token
        })
    }
}

然后在service上,只需导入config.ts文件

即可
import { Config } from '../config';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class OrganizationService {
  config = new Config;

  constructor(
    private http: HttpClient
  ) { }

  addData(data): Observable<any> {
     let sendAddLink = `${this.config.url}/api/addData`;

     return this.http.post(sendAddLink , data, this.config.httpOptions).pipe(
       tap(snap => {
      return snap;
        })
    );
 } 

我认为这是最简单,最安全的。

答案 15 :(得分:0)

我能够选择更简单的解决方案&gt;将新标题添加到默认选项合并或由api get(或其他)函数加载。

get(endpoint: string, params?: any, options?: RequestOptions) {
  if (!options) {
    options = new RequestOptions();
    options.headers = new Headers( { "Accept": "application/json" } ); <<<<
  }
  // [...] 
}

当然,您可以在默认选项或类中的任何内容中将此标题外部化。 这是在Ionic生成的api.ts @Injectable()导出类API {}

这很快,对我有用。我不想要json / ld格式。

答案 16 :(得分:0)

角度2.0.1及更高版本有一些变化:

    import {RequestOptions, RequestMethod, Headers} from '@angular/http';
    import { BrowserModule } from '@angular/platform-browser';
    import { HttpModule }     from '@angular/http';
    import { AppRoutingModule } from './app.routing.module';   
    import { AppComponent }  from './app.component';

    //you can move this class to a better place
    class GlobalHttpOptions extends RequestOptions {
        constructor() { 
          super({ 
            method: RequestMethod.Get,
            headers: new Headers({
              'MyHeader': 'MyHeaderValue',
            })
          });
        }
      }

    @NgModule({

      imports:      [ BrowserModule, HttpModule, AppRoutingModule ],
      declarations: [ AppComponent],
      bootstrap:    [ AppComponent ],
      providers:    [ { provide: RequestOptions, useClass: GlobalHttpOptions} ]
    })

    export class AppModule { }

答案 17 :(得分:0)

您可以使用一些授权标头创建自己的http客户端:

import {Injectable} from '@angular/core';
import {HttpClient, HttpHeaders} from '@angular/common/http';

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

  constructor(private http: HttpClient) {}

createAuthorizationHeader(bearerToken: string): HttpHeaders {
  const headerDict = {
    Authorization: 'Bearer ' + bearerToken,
  }
  return new HttpHeaders(headerDict);
}

get<T>(url, bearerToken) {
  this.createAuthorizationHeader(bearerToken);
  return this.http.get<T>(url, {
    headers: this.createAuthorizationHeader(bearerToken)
  });
}

post<T>(url, bearerToken, data) {
  this.createAuthorizationHeader(bearerToken);
  return this.http.post<T>(url, data, {
    headers: this.createAuthorizationHeader(bearerToken)
  });
}
}

然后将其而不是HttpClient插入您的服务类中:

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

  constructor(readonly httpClientWithAuthorization: HttpClientWithAuthorization) {}

  getSomething(): Observable<Object> {
    return this.httpClientWithAuthorization.get<Object>(url,'someBearer');
  }

  postSomething(data) {
    return this.httpClientWithAuthorization.post<Object>(url,'someBearer', data);
  }
}

答案 18 :(得分:0)

您可以使用拦截器,而不是一次又一次地为每个请求设置标头。

发出的每个请求都将通过拦截器,您可以在其中设置身份验证标头,然后释放请求。

答案 19 :(得分:0)

你可以使用拦截器的概念来实现这一点

下面是代码片段,下面的拦截方法将拦截每个请求并将apptoken附加到HTTP标头

export class MyappintercepInterceptor implements HttpInterceptor {

  constructor() {}

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

    request = request.clone({
      setHeaders: {
        'apptoken': 'SYSTEM'
      }
    });
    
    return next.handle(request);
  }
}

更多详情请参考以下网址。

https://beginnersbug.com/interceptor-in-angular/

答案 20 :(得分:-5)

您可以在路线中使用canActive,例如:

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]
  }
];

取自:https://auth0.com/blog/angular-2-authentication