TypeError: Cannot read property 'http' from undefined angular 2

After successfully implementing the gapi client in my Angular 2 app, I ran into an issue where my http object is undefined and I'm not sure why.

Below is the code: constructor (private http: Http) {}

initGmailApi() {

gapi.auth2.getAuthInstance().grantOfflineAccess().then(function(resp) {
    console.log(resp);
    const auth_code = resp.code;

    const body = {'AuthCode': auth_code};
    const headers = new Headers();
    headers.append('Content-Type', 'application/json');
    this.http.post('http://localhost:8080/startgmail', body,  headers).subscribe(
    (Response) => {
        console.log(Response);
    }
    );
});
}

      

Basically what I do is ask the user for permission to access their gmail account, and when I have a response, I would like to pass some data received to my backend server.

If I use this.http outside of the "then" clause, then the http method works fine, but it creates another problem where the "auth_code" value is not recognized.

What am I missing here?

+3


source to share


1 answer


If you want to refer to this

in the callback, don't usefunction() {}

Use arrow functions:



then((resp) => {

      

+7


source







All Articles