为什么我的变量在 angular 中的初始化时未定义?

Why is my variable undefined on init in angular?

我在我的组件上初始化服务是这样的:

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;

}

但我明白了:

ERROR TypeError: Cannot read property 'view_count' of undefined

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

感谢您的帮助。

更新:

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 });
}

尝试使用 promise 它会对您有所帮助,因为它不是 asynchronous 函数。这意味着您的代码将等到完成 http 响应。

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

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

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

但在 angular 中有 rxjs 来处理异步操作,所以你应该使用 observables...

刚刚看到。你写的 getValue1 没有 btackets...