加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Angular2 – 为每个请求设置标头

发布时间:2020-12-17 09:11:28 所属栏目:安全 来源:网络整理
导读:我需要在用户登录后为每个后续请求设置一些授权标头。 信息: 要为特定请求设置标头, import {Headers} from 'angular2/http';var headers = new Headers();headers.append(headerName,value);// HTTP POST using these headersthis.http.post(url,data,{ h
我需要在用户登录后为每个后续请求设置一些授权标头。

信息:

要为特定请求设置标头,

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

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

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

HTTP拦截器在Angular 2中不支持,但在Angular Github: https://github.com/angular/angular/issues/2684中有一个有趣的讨论。

回答,你的问题,你可以提供一个服务,包装来自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
    });
  }
}

而不是注入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 );
    });
  }
}

我也认为可以做一些事情可以使用mult提供程序为Http类提供您自己的类扩展Http一个…查看此链接:http://blog.thoughtram.io/angular2/2015/11/23/multi-providers-in-angular-2.html。

希望它帮助你,Thierry

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读