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

查看:94
本文介绍了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类使用多个提供程序来完成某些工作...请参阅此链接:

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天全站免登陆