Angular - 为每个请求设置标头 [英] Angular - Set headers for every request

查看:46
本文介绍了Angular - 为每个请求设置标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

要为特定请求设置标头,

To set headers for a particular request,

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

参考

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

But it would be not be feasible to manually set request headers for every request in this way.

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

How do I set the headers set once the user has logged in, and also remove those headers on logout?

推荐答案

要回答,您的问题是您可以提供一个服务,该服务包装来自 Angular 的原始 Http 对象.如下所述.

To answer, you question you could provide a service that wraps the original Http object from Angular. Something like described below.

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

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

And instead of injecting the Http object you could inject this one (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.

I also think that something could be done using multi providers for the Http class by providing your own class extending the Http one... See this link: http://blog.thoughtram.io/angular2/2015/11/23/multi-providers-in-angular-2.html.

这篇关于Angular - 为每个请求设置标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆