Lra*_*wls 12 javascript typescript angular
我正在向API发送请求,它返回一个数据数组,但我不知道如何从该URL中提取标题,这就是我在服务中尝试过的
@Injectable()
export class ResourcesService {
private resourcesurl = "http://localhost:9111/v1/resources";
constructor(private http: Http) { }
getResources() {
let headers = new Headers();
headers.append("api_key", "123456");
return this.http.get(this.resourcesurl, { headers: headers
}).map(this.extractData).catch(this.handleError);
}
getresourceheaders(){
let headers = new Headers();
headers.append("api_key", "123456");
let options = new RequestOptions();
let testsss = options.headers
let headerapi = this.http.request(this.resourcesurl, options);
let test = this.http.get(this.resourcesurl, { headers: headers });
console.log(headerapi);
}
private extractData(res: Response) {
let body = res.json();
return body.data || {};
}
private handleError(error: Response | any) {
let errMsg: string;
if (error instanceof Response) {
const body = error.json() || '';
const err = body.error || JSON.stringify(body);
errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
} else {
errMsg = error.message ? error.message : error.toString();
}
console.error(errMsg);
return Observable.throw(errMsg);
}
}
Run Code Online (Sandbox Code Playgroud)
我想从响应中获取标题,在这种情况下是资源
任何的想法?
csg*_*000 14
默认情况下,this.http.whatever返回的observable将返回返回的数据,而不是HttpResponse.
如果你有一个峰值:https:
//angular.io/api/common/http/HttpClient你会注意到这些选项采用了HttpObserve类型的"观察"参数.虽然它没有记录HttpObserve是什么,如果你把它作为"响应",那么你将收到一个HttpResponse<T>(https://angular.io/api/common/http/HttpResponse)的实例
所以,这是一个示例请求:
this.http.get(url, {observe: 'response'})
.subscribe(resp => console.log(resp.headers))
Run Code Online (Sandbox Code Playgroud)
注意:由于浏览器的cors安全性,Access-Control-Expose-Headers:如果您的api和angular应用程序没有相同的域,则除非API提供自定义标头,否则您将无法看到标头.
rue*_*uel 12
标头是Response类的一部分,因此您应该能够在类似的处理程序中看到它们
http.get('/path/to/resource')
.subscribe((res:Response) => {
console.log(res.headers);
// you can assign the value to any variable here
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
39204 次 |
| 最近记录: |