Angular 将http响应拆分为不同的可观察对象
我想将http响应拆分为不同的变量/可观察对象 响应是一个Json:Angular 将http响应拆分为不同的可观察对象,angular,http,Angular,Http,我想将http响应拆分为不同的变量/可观察对象 响应是一个Json: [ { "status": [ { "id": 1, "value": "active"}, { "id": 2, "value": "inactive"} ] }, { "type": [ { "id": 1, "value": "full"}, { "id": 2, "value": "half"} ] } ]
[
{
"status": [
{ "id": 1, "value": "active"},
{ "id": 2, "value": "inactive"}
]
},
{
"type": [
{ "id": 1, "value": "full"},
{ "id": 2, "value": "half"}
]
}
]
这里我想把反应分成两个不同的观察值
test.service.ts
错误:TypeError:无法读取未定义的属性“subscribe”
如果我记录组件,我会看到变量status$已填充:
状态$:ScalarObservable{u isScalar:true,值:Array2,调度程序:null}
我怎样才能避免错误并使事情正常进行?类似这样的事情:
getDropdowns(): Observable<MyType> { //Return the observable
return this.http.get(this.url)
.map((res) => <MyType>res.json());
}
let response: Observable<MyType> = getDropdowns().publishReplay(1).refCount();// Cache the reponse
status$: Observable<DropdownOption[]> = response.map(x => x[0].status)//map to get the status
type$: Observable<DropdownOption[]> = response.map(x => x[1].type)//map fot the type
尝试以下操作以避免错误: 服务台
首先,知道为什么要将其拆分为两个可观察对象是很有用的,因为您只调用一个 但如果你想这样做,你应该使用主体和观察对象: 私有子1:主题=新主题; 私有sub2:主题=新主题; 私有obs1:Observable=this.sub.asObservable; 私有obs2:Observable=this.sub.asObservable; 你的功能:任何{ this.myHttpCall.subscribedata=>{ this.sub1.nextdata.data1; this.sub2.nextdata.data2; }; } //在您的组件中 this.myService.obs1.subscribedata1=>{}; this.myService.obs2.subscribedata2=>{};
当然,我在另一个组件中使用另一个可观察到的。这只是一个例子。然后创建两个端点?不管怎么说,这段代码应该能帮你解决问题,但没有解决问题。同样的错误,没有任何改变。好的,就是这样。直到现在我才听到任何关于publishReplay的消息。我使用了一个接口:导出接口下拉选项{id:number,value:string}不匹配,现在属性状态不存在,您还有一个提示吗?您需要创建一个对象,我在其中使用MyType和use any。您可以使用DropdownOption,因为它与您的响应不匹配。
ngOnInit(){
this.testService.status$.subscribe(data => {
this.status = data;
});
}
getDropdowns(): Observable<MyType> { //Return the observable
return this.http.get(this.url)
.map((res) => <MyType>res.json());
}
let response: Observable<MyType> = getDropdowns().publishReplay(1).refCount();// Cache the reponse
status$: Observable<DropdownOption[]> = response.map(x => x[0].status)//map to get the status
type$: Observable<DropdownOption[]> = response.map(x => x[1].type)//map fot the type
getDropdowns(): void {
this.http.get(this.url)
.map((res) => {
let data = <DropdownOption[]>res.json();
for (let key in data) {
for (let k in data[key]) {
return this[k + '$'] = Observable.of(data[key][k]);
}
}
})
}