2016-09-06 95 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調用來提取它,而不是從路由數據中提取它。帶着我,抱歉。 –