user2145673
user2145673

Reputation: 363

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

After successfully implementing the gapi client in my Angular 2 app, I am now encounter an issue where my http object is undefined and I am 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 am doing is requesting a permission from the user to access his gmail account and when I have a response I would like to pass some data received to my backend server.

If I am using this.http outside the "then" clause then the http method works fine however this create another issue where the "auth_code" value is not recognized.

What am I missing here?

Upvotes: 3

Views: 4454

Answers (1)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 658155

If you want to reference this within the callback, don't use function() {}

Use instead arrow functions:

then((resp) => {

Upvotes: 8

Related Questions