使用RequestOptions有条件地向HTTP请求添加标头

时间:2017-05-23 10:55:34

标签: angular http http-headers angular-http

在我的Angular2应用程序中,我使用扩展CustomRequestOptions的{​​{1}}类为每个请求设置标头值。

BaseRequestOptions

如您所见,内容类型设置为@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

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

现在我的问题是关于我要做的事情的有效性。如果它无效,请指出我的方法来做到这一点。谢谢..!

2 个答案:

答案 0 :(得分: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,因此每个请求都有来自基本服务的自定义标头。

答案 1 :(得分:0)

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

然后,下次调用merge方法时,会检查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');
 }