typescript 将 Observable.forkJoin 的结果转换为 Angular 2 中各自的类型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45306324/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Casting results from Observable.forkJoin to their respective types in Angular 2
提问by Chris Lees
Let say I have a component in Angular 2 that needs to load 2 different things from the server before the page is displayed. I'd like all of those things to fire off and call one event handler when they come back telling the page isLoaded = true. Let's say I have a service class that looks like this.
假设我在 Angular 2 中有一个组件,它需要在显示页面之前从服务器加载 2 个不同的东西。我希望所有这些事情都被触发并在他们回来告诉页面 isLoaded = true 时调用一个事件处理程序。假设我有一个看起来像这样的服务类。
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());
}
}
Then I have a component that uses that service class like this.
然后我有一个像这样使用该服务类的组件。
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;
});
}
}
The TypeScript compiler is complaining that it cant convert type object to type StrongData1[]. If I change StrongData1 and StrongData2 to "any", everything works fine. I'd rather not do that though because I'm losing the benefit of TypeScript's strong typings.
TypeScript 编译器抱怨它无法将类型对象转换为类型 StrongData1[]。如果我将 StrongData1 和 StrongData2 更改为“any”,则一切正常。我宁愿不这样做,因为我失去了 TypeScript 强类型的好处。
How do I cast the results from forkJoin to their respective types?
如何将 forkJoin 的结果转换为它们各自的类型?
回答by Nicolas Gehlert
for me it always works when i add the requests directly to the Observable.forkJoin and then use es6 destructing for the result array.
对我来说,当我将请求直接添加到 Observable.forkJoin 然后对结果数组使用 es6 析构时,它总是有效。
so your code could look like this
所以你的代码看起来像这样
Observable
.forkJoin(this.myService.getStronglyTypedData1(), this.myService.getStronglyTypedData2())
.subscribe(
([typeData1, typeData2]) => {
this.stronglyTypedData1 = typeData1;
this.stronglyTypedData2 = typeData2;
this.isLoaded = true;
}
);
回答by kit
try
尝试
(results:[StrongData1[], StrongData2[]]) =>