如何在渲染组件之前使Angular2等待一个promise

时间:2016-09-06 22:41:04

标签: angular resolver

首先:是的,我事先用谷歌搜索过,而solution出现的对我来说并不适合。

上下文

我有一个调用服务的Angular 2组件,并且在收到响应后需要执行一些数据操作:

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

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

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

这导致一个错误,即孩子将myData定义为未定义。上面发布的Google搜索结果说明了使用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属性时仍然如此:

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

使用此界面是否已更改?

1 个答案:

答案 0 :(得分:4)

路由器支持从resolve()返回的promise或observable 另请参阅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