我已经使用Angular / RxJS几周了,并且有多个模型是从多个REST请求中构建的,到目前为止我使用switchMap()实现了这一点。这里是一个简单的虚构示例(stackblitz:https://stackblitz.com/edit/angular-o1djbb):
import { Component, OnInit, } from '@angular/core';
import { Observable, of } from 'rxjs';
import { delay, switchMap } from 'rxjs/operators';
interface Order {
id: string;
itemName: string;
details?: string;
}
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
order: Order;
ngOnInit() {
this.getOrderFromApi(123)
.subscribe(item => this.order = item);
}
getOrderFromApi(id): Observable<Order> {
const item$ = this.getItemName(id);
const fullItem$ = item$.pipe(
switchMap(n => {
console.log(`Got name: '${n}''`);
return this.getDetails(n);
},
(nameReq, detailsReq) => ({ id: '123', itemName: nameReq, details: detailsReq })
));
return fullItem$;
}
getItemName(id): Observable<string> {
return this.fakeXhr('foo');
}
getDetails(itemName): Observable<string> {
console.log(`Got details '${itemName}''`)
return this.fakeXhr('Some details about foo');
}
fakeXhr(payload: any) {
return of(payload)
.pipe(delay(2000));
}
}
还有一个简单的模板:
<p>
item: {{order && order.itemName}}
</p>
<p>
details: {{order && order.details}}
</p>
这样做可以实现功能,但是订单信息直到 两个 请求都完成后才会被渲染。我希望的是,在可用时尽快呈现 itemName,然后在详情可用时再呈现它们。因此,利用可观察对象可以发出多个值的优势,例如:
// first value emitted:
{ itemName: 'foo', details: null }
// second value emitted:
{ itemName: 'foo', details: 'Some details about foo' }
我意识到我可能可以使用BehaviorSubject或Redux(就像我以前在React中做的那样)来实现这一点,但是由于这对我来说还很新,所以感觉有一个简单的解决方案我无法完全掌握。
expand
也非常适合执行未知数量的请求,例如当您处理分页时。https://dev59.com/WLHma4cB1Zd3GeqPI0Rv#54293624 - frido