2017-05-23 73 views
0

在我的Angular2应用程序中,我使用CustomRequestOptions类(其扩展BaseRequestOptions)为每个请求设置标题值。有条件地使用RequestOptions向HTTP请求添加头文件

@Injectable() 
export class CustomRequestOptions extends BaseRequestOptions { 
    constructor(private _globals: Globals) { 
     super(); 
     this.headers.set('Content-Type', 'application/json'); 
     this.headers.set('X-Requested-By', 'Angular 2'); 
    } 

    merge(options?: RequestOptionsArgs): RequestOptions { 

     // can I access the headers here I have set when the request is made ? 
     // and then conditionally set Content-Type 

     var newOptions = super.merge(options); 
     let hdr = this._globals.getAuthorization(); 

     newOptions.headers.set("Authorization", hdr); 

     return newOptions; 
    } 

} 

如您所见,内容类型设置为application/json

现在我有要求将照片上传到服务器。只能为该请求清除内容类型。

我想用的方法是为请求设置一些标题值,在merge方法内获取该值并有条件地清除内容类型标题。

设置自定义首部的请求被声明时: -

let formData: FormData = new FormData(); 
formData.append('file', photoToSave); 

let headers = new Headers(); 
//setting a custom header 
headers.append('from', 'photo-upload'); 
let options = new RequestOptions(); 
options.headers = headers; 

let savedPath = this._http 
    .post(this._endpointUrl + "save-photo", formData, options) 
    .map(
    res => { 
     return res.json(); 
    } 
    ) 
    .catch(handleError); 

访问在合并方法所添加的报头。这是我遇到问题的地方。我可以做我想做的事吗? ?我试图以此为起点。但是被访问的头文件是空的。请参阅代码中的评论。

merge(options?: RequestOptionsArgs): RequestOptions { 

    console.log("options header = " + options.headers); //this prints null 
    console.log("options body = " + options.body); 

    var newOptions = super.merge(options); 

    if(from header equal to 'photo-upload'){ 
     newOptions.headers.set('Content-Type', ''); 
    }else{ 
     newOptions.headers.set('Content-Type', 'application/json'); 
    } 

    let hdr = this._globals.getAuthorization(); 
    newOptions.headers.set("Authorization", hdr); 

    return newOptions; 
} 

现在我的问题是关于我想要做的事情的有效性。如果无效,请指出一条办法。谢谢..!

回答

3

对于这个东西,您可以创建一个基本服务,并在该服务中,您可以为每个API请求设置标题。

BaseService文件

import { Injectable } from "@angular/core"; 
import { Http, RequestOptions, Headers } from "@angular/http"; 

@Injectable() 
export class BaseService { 

    public apiUrl :string = 'your api url'; 

    constructor(private http: Http) {   
    } 

    get(url: any) { 

     return this.http.get(this.apiUrl + url).do(data => { 
      console.log(data); 
     }); 
    } 

    post(url: any, data: any) { 

     //Add uesr id every time for authentication 
     if (data != null) { 
      data.user_id = this.userId; 
     } 
     let headers = new Headers({ 'Content-Type': 'application/json' }); 
     let options = new RequestOptions({ headers: headers }); 

     try { 
      return this.http.post(this.apiUrl + url, Json.serialize(data), options).do(data => { 

       if (data != null && data.statusText != "No Content") { 
        console.log("Response Data - ", data.json()); 
        //data.statusText ="No Content","OK"; 
       } 
      }); 
     } 
     catch (e) { 
      console.log(e); 
      return null; 
     } 
    } 

} 

APIService文件

import { Injectable } from "@angular/core"; 
import { Response } from "@angular/http"; 
import { Observable } from 'rxjs/Observable'; 

@Injectable() 
export class ApiService { 

    constructor(public http: BaseService) { 

    } 

     //Toolbar 
     public GetToolbarCollection(id: any): any { 
      let data = { 
       id: id 
      }; 

      return this.http.post('GetToolbarCollection', data) 
       .map((response: Response) => { 
        return new ToolbarCollection(response.json()); 
       }) 
       .catch(this.handleError); 
     } 

     public SetToolbarCollection(toolbarCollection: ToolbarCollection): any { 

      let data = { 
       toolbarCollection: toolbarCollection 
      }; 

      return this.http.post('Portal/SetToolbarCollection', data) 
       .map((response: Response) => { 
        return new ToolbarCollection(response.json()); 
       }) 
       .catch(this.handleError); 
     } 

     private handleError(error: Response) { 
     HideLoader(); 
     console.error(error); 
     return Observable.throw(error.json().error || 'Server error'); 
    } 
} 

在上面的代码中BaseService有两种方法,包括get和set。在ApiService里面我使用BaseService,所以每个请求都会有基本服务的自定义头。

0

我能够通过将变量from存储在浏览器的本地存储中而不是将其添加为标题来解决此问题。该变量被分配名称"photo-upload"。 (不管你喜欢什么名字)

然后,下一次调用合并方法,那么from变量被检查。如果它包含值"photo-upload",我只是忽略。如果它不等于"photo-upload"我设置标头值newOptions.headers.set('Content-Type', 'application/json');

if(localStorage.get("from") === "photo-upload"){ 
    newOptions.headers.set('Content-Type', ''); 
}else{ 
    newOptions.headers.set('Content-Type', 'application/json'); 
}