我想将http响应拆分为不同的Variables / Observables。
响应是Json:
with t (url) as (
values
('http://some.host/some/path?oid=abc123&other'),
('http://some.host/some/path?other&oid=def456&foo=bar')
)
select split_part(substring(url from 'oid=\w+'), '=', 2)
from t;
在这里,我想将响应拆分为2个不同的Observable。
test.service.ts
split_part
----------
abc123
def456
app.component.ts
[
{
"status": [
{ "id": 1, "value": "active"},
{ "id": 2, "value": "inactive"}
]
},
{
"type": [
{ "id": 1, "value": "full"},
{ "id": 2, "value": "half"}
]
}
]
错误: TypeError:无法读取未定义的属性'subscribe'
如果我记录组件,我看到变量status $被填充: status $:ScalarObservable {_isScalar:true,value:Array(2),scheduler:null}
我如何避免错误并使事情有效?
答案 0 :(得分:1)
这样的事情:
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 :(得分:0)
尝试这样做以避免错误:
<强> service.ts 强>
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]);
}
}
})
}
答案 2 :(得分:0)
首先,知道为什么将其拆分为2个可观察对象会很有用,因为你只需要调用一个。
但是如果你想这样做,你应该使用Subjects and Observables:
private sub1: Subject<any> = new Subject();
private sub2: Subject<any> = new Subject();
private obs1: Observable<any> = this.sub.asObservable();
private obs2: Observable<any> = this.sub.asObservable();
yourFunction(): any {
this.myHttpCall().subscribe(data => {
this.sub1.next(data.data1);
this.sub2.next(data.data2);
});
}
// In your components
this.myService.obs1.subscribe(data1 => {});
this.myService.obs2.subscribe(data2 => {});