如何将标题附加到某些路由而不是全部

时间:2018-05-31 20:17:12

标签: angular

我正在尝试将角度Http和Headers更新为angular 4 HttpClient和HttpHeaders模块。我遇到的问题是我想只为一两条路线添加验证标题,而不是我的所有路由。我发现的许多教程只向我展示了如何更新所有路由的标头,我不完全理解angular.io头文件api来更新我的代码。

我的旧代码

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

constructor(private http: Http) { }

  authenticateUser(user) {
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    return this.http.post('http://localhost:3000/users/authenticate', user, { headers: headers });
      .map(res => res.json());
  }

  getProfile() {
    let headers = new Headers();
    this.loadToken();
    headers.append('Authorization', this.authToken);
    headers.append('Content-Type', 'application/json');
    return this.http.get('http://localhost:3000/users/profile', { headers: headers });
      .map(res => res.json());

新代码

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

const httpOptions = {
  headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};

constructor(private http: HttpClient) { }

  authenticateUser(user) {
    return this.http.post('http://localhost:3000/users/authenticate', user, httpOptions);
  }

  getProfile() {
    this.loadToken();
    headers.append('Authorization', this.authToken);  <---- not sure what to do with this    
    return this.http.get('http://localhost:3000/users/profile', httpOptions);

1 个答案:

答案 0 :(得分:0)

每次使用工厂函数创建httpOptions,并传递参数以定义所需的标题。

private getOptions(authToken?: string) {
   const httpOptions = {
        headers: new HttpHeaders({ 'Content-Type': 'application/json' })
   };
   if(authToken) {
       httpOptions.headers.append('Authorization', authToken);
   }
   return httpOptions;
}

authenticateUser(user) {
     return this.http.post('http://localhost:3000/users/authenticate', user, this.getOptions()).map(res => res.json());
}

getProfile() {
    const token = this.loadToken();
    return this.http.get('http://localhost:3000/users/profile', this.getOptions(token));
}