为什么我的变量在init中以角度未定义?

时间:2018-04-30 16:15:57

标签: javascript angular service init

我在我的组件上初始化服务,如下所示:

ngOnInit() {
    this.getValue1();
    this.getValue2();
    this.getValue3();
}

当服务获得数据时,我想这样做:

ngOnInit() {
    this.getValue1();
    this.getValue2();
    this.getValue3();
    this.result = this.value1.view_count.value + this.value2.view_count.value + this.value3.view_count.value;

}

但我得到了:

  

错误类型错误:无法读取未定义的属性“view_count”

我如何等待服务结果对我的操作有效?

感谢您的帮助。

更新

getvalue1(): void {
    this.subscription=this.dataService.getViews(360001167865).subscribe(data => {
        this.value1 = data;
    });
}

service.ts:

 getViews(id: number): Observable<any> {
    return this.http.get(this.URL + "views/" + id + "/count.json", { headers: headers });
}

2 个答案:

答案 0 :(得分:0)

尝试使用承诺它会对您有所帮助,因为它不是异步功能。这意味着您的代码将等到完成http响应。

this._http.get('API URL').map(res => res.json()).toPromise()

答案 1 :(得分:0)

你可以让你的funcs异步等待一些数据

async getValue1() {
    result = await myAsyncOperation();
    return result;
}

但是在角度上有rxjs来处理异步操作所以你应该使用observables ......

只是看到了。你写了没有btackets的getValue1 ......