0

So, I have been trying access my services inside a promise callback. I have added all necessary modules and imported them into my file. I have also declared them in the constructor.

//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 

Edit: The issue turned out to be an issue in my understanding to the context of the 'this' keyword, but not in angular services.

A NASR
  • 3
  • 5

2 Answers2

2

Change this

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

to this

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

clousures has no this context so you must bind it.

Antoniossss
  • 31,590
  • 6
  • 57
  • 99
1

As already mentioned in some comments, the this context is not what you expect. Either use .bind(this) or use the lambda syntax.

clicked() {
   this.http.get(..)
      .toPromise()
      .then(response => this.loginCallbackHandler(response))
      .catch(error => console.log(error));
}

I'd recommend reading up on how this context behaves in JavaScript (and therefore in TypeScript). This would be a good start.

On another note, you could also use async/await if you want to use promises.

async clicked() {
   try {
      const response = await this.http.get(..).toPromise();
      this.loginCallbackHandler(response) ;
   } catch (error) {
      console.log(error);
   } 
}
pascalpuetz
  • 5,238
  • 1
  • 13
  • 26