Angular2 – 为每个请求设置标头

前端之家收集整理的这篇文章主要介绍了Angular2 – 为每个请求设置标头前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我需要在用户登录后为每个后续请求设置一些授权标头。 @H_404_1@信息:

@H_404_1@要为特定请求设置标头,

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
@H_404_1@Reference

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

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

HTTP拦截器在Angular 2中不支持,但在Angular Github: https://github.com/angular/angular/issues/2684中有一个有趣的讨论。 @H_404_1@回答,你的问题,你可以提供一个服务,包装来自Angular2的原始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,{
      headers: headers
    });
  }
}
@H_404_1@而不是注入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 );
    });
  }
}
@H_404_1@我也认为可以做一些事情可以使用mult提供程序为Http类提供您自己的类扩展Http一个…查看此链接http://blog.thoughtram.io/angular2/2015/11/23/multi-providers-in-angular-2.html

@H_404_1@希望它帮助你,Thierry

原文链接:https://www.f2er.com/angularjs/147038.html

猜你在找的Angularjs相关文章