从Observable.forkJoin到Angular 2中各自类型的转换结果
假设Angular 2中有一个组件,在显示页面之前需要从服务器加载2个不同的东西。我希望所有这些东西都能启动,当它们返回告诉页面isLoaded=true时,调用一个事件处理程序。假设我有一个类似这样的服务类从Observable.forkJoin到Angular 2中各自类型的转换结果,angular,typescript,rxjs,Angular,Typescript,Rxjs,假设Angular 2中有一个组件,在显示页面之前需要从服务器加载2个不同的东西。我希望所有这些东西都能启动,当它们返回告诉页面isLoaded=true时,调用一个事件处理程序。假设我有一个类似这样的服务类 export class MyService { getStronglyTypedData1(): Observable<StrongData1[]>{ return this.http.get('http://...').map((response:Resp
export class MyService {
getStronglyTypedData1(): Observable<StrongData1[]>{
return this.http.get('http://...').map((response:Response) => <StrongData1[]>response.json());
}
getStronglyTypedData2(): Observable<StrongData2[]>{
return this.http.get('http://...').map((response:Response) => <StrongData2[]>response.json());
}
}
export class MyComponent implements OnInit {
isLoaded = false;
stronglyTypedData1: StrongData1[];
stronglyTypedData2: StrongData2[];
constructor(private myService:MyService){ }
ngOnInit(){
var requests [
this.myService.getStronglyTypedData1(),
this.myService.getStronglyTypedData2()
];
Observable.forkJoin(requests).subscribe(
results => {
this.stronglyTypedData1 = results[0];
this.stronglyTypedData2 = results[1];
this.isLoaded = true;
});
}
}
TypeScript编译器抱怨无法将类型对象转换为类型StrongData1[]。如果我将StrongData1和StrongData2更改为“任意”,则一切正常。不过我不想这样做,因为我正在失去TypeScript强大的打字功能的好处
如何将forkJoin的结果强制转换为它们各自的类型?试试看
(results:[StrongData1[], StrongData2[]]) =>
对我来说,当我将请求直接添加到Observable.forkJoin,然后对结果数组使用es6销毁时,它总是有效的 所以你的代码看起来像这样
Observable
.forkJoin(this.myService.getStronglyTypedData1(), this.myService.getStronglyTypedData2())
.subscribe(
([typeData1, typeData2]) => {
this.stronglyTypedData1 = typeData1;
this.stronglyTypedData2 = typeData2;
this.isLoaded = true;
}
);
在Typescript中,您可以对函数参数(本例中为元组)使用解构:
不同之处在于,当使用forkJoin传入数组时,将出现类型检查错误。您不必将请求直接添加到Observable.forkJoin。您可以执行
var request1=this.myService.getStronglyTypedData1();var request2=this.myService.getStronglyTypedData2()
thenObservable.forkJoin(request1,request2).subscribe(results=>{type1=results[0];type2=results[1]}
或es6 destructionObservable.forkJoin(request1,request2).subscribe([type1,type2])=>{type1=type1;type2=type2})
如果你像我一样看不到它:不要将数组传递给forkJoin([typedReq1,typedReq2])
,而是直接添加可观察对象:forkJoin(typedReq1,typedReq2)
并且ES6破坏变量将被键入。这似乎在RxJs 6中被弃用。对于RxJs 6,您应该直接使用从RxJs导入的forkJoin,而不是Observable。ForkJoint引发异常,如“结果必须是StrongData1[]”。您可以编写数组。但是@Nicolas Gehlert的回答很好。
const requests = [
this.myService.getStronglyTypedData1(),
this.myService.getStronglyTypedData2()
];
forkJoin(requests)
.subscribe(([data1, data2]: [StrongData1[], StrongData2[]]) => {
this.stronglyTypedData1 = data1;
this.stronglyTypedData2 = data2;
this.isLoaded = true;
});