如何在构造函数Angular 2上使用Async调用注入服务

Mig*_*ada 7 javascript http promise typescript angular

这是问题:我有一个服务在构造函数中发出HTTP请求:

    constructor(public http: Http, public geolocation: Geolocation) {
        this.http = http;
        this.geolocation = geolocation;
        //Http request... this will set variable forecast of the class when complete.
        this.getForecast(16);
    }
Run Code Online (Sandbox Code Playgroud)

然后我在这样的组件中注入该服务:

    constructor(public connector: ApiConnector) {
         this.forecast = connector.forecast;
    }
Run Code Online (Sandbox Code Playgroud)

如果我尝试在组件装饰器上使用组件类的预测成员,就像我在这里一样:

@Component({
    selector: 'app',
    directives: [MainForecast, DailyForecast],
    template: `
        <main-forecast [main-weather]="forecast"></main-forecast>
        <daily-forecast [weather-list]="forecast.list"></daily-forecast>
    `,
})
Run Code Online (Sandbox Code Playgroud)

我收到一个错误,"无法读取未定义的属性'列表'......"

是否有可能在组件构造函数中使用promises?

dan*_*y74 0

Angular2 建议在ngOnInit内部而不是在构造函数内部做繁重的工作。

ngOnInit是一个生命周期钩子/事件。

  • *ngOnInit* 适用于组件,不适用于服务(可注入) (8认同)