angular - 角度服务是否可以从异步上下文中访问?
问题描述
所以,我一直在尝试在 promise 回调中访问我的服务。我已经添加了所有必要的模块并将它们导入到我的文件中。我还在构造函数中声明了它们。
//This is part of my login Component Class and this line code is bound to a //button click
clicked(){
this.http.get(..)toPromise().then( this.loginCallbackHandler ).catch((error) => console.log(error));
//any service accessed here works fine example
console.log(this.app)// this is fine here
}
//
loginCallbackHandler(reponse){
//accessing any service from here produces the the error below (error1)
//For example
console.log(this.html)
//Or
console.log(this.app)
}
//constructor definition
constructor(@Host() public app: AppComponent,
private oauthService: OAuthService,
private http: HttpClient
){}
//Error1
ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'html' of undefined
TypeError: Cannot read property 'html' of undefined
at push../src/app/login/login.page.ts.LoginPage.loginCallbackHandler (login.page.ts:64)
at
编辑:在我对“this”关键字上下文的理解中,这个问题原来是一个问题,而不是在角度服务中。
解决方案
改变这个
this.http.get(..)toPromise().then( this.loginCallbackHandler )
对此
this.http.get(..)toPromise().then( this.loginCallbackHandler.bind(this) )
clousures 没有this
上下文,所以你必须绑定它。
推荐阅读
- vpn - Freeradius 代理设置和 Strongswan
- python - 有没有办法从机器人框架中获取当前的 imaplibrary 实例并传递给单独的 python 函数?
- security - 如何在没有密码的情况下从 p12 文件中提取字段(国家、州、...电子邮件)
- javascript - 如何找到本机光标的中心并将自定义光标与其对齐?
- python-3.x - Faulty bubble sort using recursion on slices; list does not end up sorted
- javascript - How to search for value in text which is starting and ending with the same symbol but the numbers between are different every time? NodeJS
- javascript - can't add currency format to the total input in a sum of inputs
- python-3.x - 为什么我可以刮一张表,但不能刮一张嵌套表?
- python - 如何在不杀死未完成的芹菜任务的情况下重新启动heroku应用程序
- pdf - 如何在 Android/iOS 中处理 GeoPDF