我对 Angular 2 和 Typescript 还很陌生,想构建一个卡片搜索应用程序。 基本上我有一个存储和观察响应数据的组件......
this.searchFormGroup.valueChanges
.debounceTime(200)
.distinctUntilChanged()
.switchMap(searchFormGroup => this.mtgService.getCardsByName(searchFormGroup))
.subscribe(
searchResult => {
this.searchResult = searchResult.cards;
},
err => {
console.log(err);
});
...和一个服务,它将 http.get 请求发送到 API ...
getCardsByName(searchFormGroup){
this.params.set(...) ...
return this.http.get(this.nameUrl, { search: this.params })
.map(res => res.json())
.catch((error:any) => Observable.throw(error.json().error || 'Server error'))}
...相互交流。
在组件内存储来自请求的 header 数据的最佳方式是什么?基本上我需要请求的总卡数和分页链接,它们在响应 header 中可用。几个小时以来,我一直在努力寻找解决方案 :o
最佳答案
好的尝试和错误让我解决了这个问题: 组件激活服务的 http.get -> 服务响应 res.json() -> 组件仅在 JSON 中获得 res,似乎删除了响应 header 。 我的解决方法是:
组件:
this.searchFormGroup.valueChanges
.debounceTime(200)
.distinctUntilChanged()
.switchMap(searchFormGroup => this.mtgService.getCardsByName(searchFormGroup))
.subscribe(
res => {
console.log(res.headers); //works fine now!
this.searchResult = res.json().cards;
},
err => {
console.log(err);
});
服务:
getCardsByName(searchFormGroup){
this.params.set(...) ...
return this.http.get(this.nameUrl, { search: this.params })
.catch((error:any) => Observable.throw(error.json().error || 'Server error')) }
所以完整的资源现在被传递回组件。
但是:有什么技巧可以使它变得更好吗?
关于http - angular2 如何将来自 http.get 的响应头数据存储在额外变量中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41290241/