如何使Angular2在渲染组件之前等待一个承诺 [英] How to make Angular2 wait for a promise before rendering component
问题描述
First: Yes, I have Googled this beforehand, and the solution that came up isn't working for me.
上下文
我有一个Angular 2组件来调用服务,并且一旦收到响应,就需要执行一些数据操作:
I have an Angular 2 component that calls a service, and needs to perform some data manipulation once it receives the response:
ngOnInit () {
myService.getData()
.then((data) => {
this.myData = /* manipulate data */ ;
})
.catch(console.error);
}
在其模板中,该数据将传递到子组件:
In its template, that data is passed to a child component:
<child-component [myData]="myData"></child-component>
这将导致错误,表明孩子正在获得myData
的未定义值.上面发布的Google结果讨论了使用Resolver
的问题,但这对我不起作用.
This is causing an error that the child is getting myData
as undefined. The Google result posted above talks about using Resolver
but that isn't working for me.
当我创建一个新的解析器时:
When I create a new resolver:
import { Injectable } from '@angular/core';
import { Resolve, ActivatedRouteSnapshot } from '@angular/router';
import { Observable } from 'rxjs/Rx';
import { MyService } from './my.service';
@Injectable()
export class MyResolver implements Resolve<any> {
constructor(private myService: MyService) {}
resolve (route: ActivatedRouteSnapshot): Observable<any> {
return Observable.from(this.myService.getData());
}
}
app.routing.ts
const appRoutes: Routes = [
{
path: 'my-component',
component: MyComponent,
resolve: {
myData: MyDataResolver
}
}
];
export const routing = RouterModule.forRoot(appRoutes);
我收到一个错误,提示MyDataResolver
没有提供者.当我将MyDataResolver
添加到 app.component.ts 中的providers
属性中时,情况仍然如此:
I get an error that there is no provider for MyDataResolver
. This is still the case when I add MyDataResolver
to the providers
property in app.component.ts:
@Component({
selector: 'my-app',
templateUrl: 'app/app.component.html',
providers: [
MyService,
MyResolver
]
})
使用此接口的界面已更改吗?
Has the interface for using this changed?
推荐答案
路由器支持从resolve()
返回的Promise或Observable.
另请参见 https://angular.io/docs/ts/latest/api/router/index/Resolve-interface.html
The router supports a promise or an observable returned from resolve()
.
See also https://angular.io/docs/ts/latest/api/router/index/Resolve-interface.html
这应该做您想要的:
@Injectable()
export class MyResolver implements Resolve<any> {
constructor(private myService: MyService) {}
resolve (route: ActivatedRouteSnapshot): Promise<any> {
return this.myService.getData();
}
}
另请参见 https://angular.io/docs/ts/latest/guide/router.html#!#resolve-guard
这篇关于如何使Angular2在渲染组件之前等待一个承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!