将 Observable<B> 转换为对象 B
Converting Observable<B> to object B
我正在使用 Angular 2 和 RxJs。我得到以下编译异常,
[ts]
Type 'Observable<Observable<B>>' is not assignable to type
'Observable<B>'.
Type 'Observable<B>' is not assignable to type 'B'.
Property 'id' is missing in type 'Observable<B>'.
下面是有问题的代码。我无法真正更改 'getB' 的方法签名,因为我正在覆盖它。基本方法不需要第二次 API 调用来填充子项,因此可以覆盖。
export interface A {
b: B;
}
export class B {
cList: C[];
}
export interface C {
name: string;
type: string;
}
getB(): Observable<B> {
let entries = <A[]> []; // get A[] via an server call
// in this case entries will have only one element in the array
return this.loadBChilds(entries[0])
.map(e => e.b);
}
loadBChilds(a: A): Observable<A> {
// API call to fetch childs
// set childs to a.b.List
return this.rest.get('someapi')
.map(res => {
res.record.map(r => this.setData(r));
return a;
});
}
知道如何实现吗?
TIA
设法解决了这个问题。解决方法是折叠通过 flatMap 从第一个 API 接收到的第一个数组,然后将其用于后续 API 调用。
getB(): Observable<B> {
return this.rest.get('firstapi')
.flatMap(res => {
let entries = res.record
.map(record => this.getEntry(record));
return this.loadBChilds(entries[0])
.map(e => e.b);
});
}
我正在使用 Angular 2 和 RxJs。我得到以下编译异常,
[ts]
Type 'Observable<Observable<B>>' is not assignable to type
'Observable<B>'.
Type 'Observable<B>' is not assignable to type 'B'.
Property 'id' is missing in type 'Observable<B>'.
下面是有问题的代码。我无法真正更改 'getB' 的方法签名,因为我正在覆盖它。基本方法不需要第二次 API 调用来填充子项,因此可以覆盖。
export interface A {
b: B;
}
export class B {
cList: C[];
}
export interface C {
name: string;
type: string;
}
getB(): Observable<B> {
let entries = <A[]> []; // get A[] via an server call
// in this case entries will have only one element in the array
return this.loadBChilds(entries[0])
.map(e => e.b);
}
loadBChilds(a: A): Observable<A> {
// API call to fetch childs
// set childs to a.b.List
return this.rest.get('someapi')
.map(res => {
res.record.map(r => this.setData(r));
return a;
});
}
知道如何实现吗?
TIA
设法解决了这个问题。解决方法是折叠通过 flatMap 从第一个 API 接收到的第一个数组,然后将其用于后续 API 调用。
getB(): Observable<B> {
return this.rest.get('firstapi')
.flatMap(res => {
let entries = res.record
.map(record => this.getEntry(record));
return this.loadBChilds(entries[0])
.map(e => e.b);
});
}