Javascript 为什么我的变量在init中没有定义?
我在我的组件上初始化服务,如下所示:Javascript 为什么我的变量在init中没有定义?,javascript,angular,service,init,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.
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\u 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 });
}
getViews(id:number):可观察{
返回this.http.get(this.URL+“views/”+id+“/count.json”,{headers:headers});
}
尝试使用承诺它将帮助您,因为它不是异步函数。这意味着您的代码将等待http响应完成
this._http.get('API URL').map(res => res.json()).toPromise()
您可以使函数异步以等待某些数据
async getValue1() {
result = await myAsyncOperation();
return result;
}
但是在angular中有rxjs来处理异步操作,所以您应该使用Observable
刚刚看到。您编写的getValue1没有数据包…我们需要更多信息。您能为
getValue1
函数添加代码吗?它是异步的吗?应该是这个.getValue1().view\u count吗?如果目的是调用一个方法,那么您需要使用括号。这似乎是可行的,因为在javascript中,函数是一个带有字段的对象,它在该对象中找不到任何view\u count字段。感谢您的回复。关键是,所有内容都是异步的,所以它不会等待获得值1、2和3来进行最后一次操作。否则可以使用Rxjs ForkJoin。对不起,我发邮件时失败了。当我使用async/await时,它不适用于我。谢谢你的帮助,我正在使用Observable,我更新了我的帖子。谢谢你的帮助