2016-09-06 90 views
6

首先:是的,我已经事先谷歌搜索,并且solution出现了不适合我。如何让Angular2在渲染组件之前等待诺言

语境

我有一个角2成分调用的服务,并且需要一旦接收到该响应执行一些数据操作:

ngOnInit() { 
    myService.getData() 
    .then((data) => { 
     this.myData = /* manipulate data */ ; 
    }) 
    .catch(console.error); 
} 

在其模板中,该数据是传递给子组件:

<child-component [myData]="myData"></child-component> 

这是导致孩子出错的错误myData未定义。上面发布的谷歌结果谈到了使用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。这仍是如此,当我在app.component.ts添加MyDataResolverproviders属性:

@Component({ 
    selector: 'my-app', 
    templateUrl: 'app/app.component.html', 
    providers: [ 
     MyService, 
     MyResolver 
    ] 
}) 

一直使用这个接口改变了吗?

+0

你可以实现“myData的”孩子的财产作为setter和检查“未定义”呢? – rook

+0

它是'MyResolver'还是'MyDataResolver'。您的问题中的代码似乎不一致。 –

回答

3

路由器支持从resolve()返回的承诺或观察值。
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

+0

基于第二个链接,我已经在** app.module.ts **中将'MyResolver'添加到'providers',但是'child-component'仍然是错误的,因为它将数据定义为undefined。似乎它在父组件拥有数据之前仍在实例化。这可能是因为父组件是什么等待解析器,而不是子组件?但是子组件没有与之关联的路由,父组件是获取数据的组件,所以我不知道如何让它等待。 –

+0

很难说明你的代码在这个描述中究竟做了什么。最简单的方法是添加'* ngIf',就像'' –

+1

我的错误。我仍然试图通过父组件的构造函数中的REST调用来提取它,而不是从路由数据中提取它。带着我,抱歉。 –