2017-01-18 121 views
1

在getReport服務返回數據之前,組件的ngOninit被擊中。它不會等待服務被解析。Angular 2組件在路由被解析之前被加載

路由:

@Injectable() 
class ReportResolver implements Resolve<any> { 
constructor(private reportsService: ReportsService) { 
} 
resolve(
    route: ActivatedRouteSnapshot, 
    state: RouterStateSnapshot 
): any { 
    this.reportsService.GetReport(route.params["id"]).subscribe((data: any) => { 
     return data; 
    }); 
}} 

const appRoutes: Routes = [ 
{ 
    path: "reports/:id", 
    component: TabularReportsFachadeComponent, 
    resolve: { report: ReportResolver } 
}, 
{ 
    path: "", 
    component: DashboardComponent 
},]; 

服務:

GetReport(id: any): Observable<any> { 
    return this._http.get("api/reports/?" + id).map(res => res.json()); 
} 

組件:

ngOnInit(): void { 
    debugger 
    this.report = this.route.snapshot.data["report"].data; 

} 

ngOninit是獲得getReport

回答

1

之​​前打組件應返回Observable,而不是Subscription。實際上,您的resolve不會返回任何內容,但您不應撥打Observable上的subscribe(),因爲這會返回Subscription

如果您需要在返回前處理該值,請改爲使用map((val) => ...)或其他某個運算符。

resolve(
    route: ActivatedRouteSnapshot, 
    state: RouterStateSnapshot 
): any { 
    return this.reportsService.GetReport(route.params["id"]) 
}} 
+0

我刪除了訂閱,它工作。謝謝! – janIreal23

+0

很高興聽到:)感謝您的反饋。 –

相關問題