首页 > 解决方案 > 角度服务是否可以从异步上下文中访问?

问题描述

所以,我一直在尝试在 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”关键字上下文的理解中,这个问题原来是一个问题,而不是在角度服务中。

标签: angulartypescript

解决方案


改变这个

this.http.get(..)toPromise().then( this.loginCallbackHandler )

对此

this.http.get(..)toPromise().then( this.loginCallbackHandler.bind(this) )

clousures 没有this上下文,所以你必须绑定它。


推荐阅读