在我的Angular2应用程序中,我使用扩展BaseRequestOptions的CustomRequestOptions类为每个请求设置标头值。
@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;
}
}如您所见,Content Type设置为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方法中访问添加的标头。这就是我的问题所在。我能做我想做的事吗??我试着把它作为一个起点。但是访问的报头为空。请参阅代码中的注释。
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;
}现在我的问题是关于我试图做的事情的有效性。如果无效,请给我指出一种方法。谢谢你..!
发布于 2017-05-23 19:15:58
对于这些东西,您可以创建一个基础服务,并且在该服务中,您可以为每个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,所以每个请求都会有来自基础服务的自定义头部。
发布于 2017-05-29 19:10:00
我能够通过将变量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');
}https://stackoverflow.com/questions/44132833
复制相似问题