3

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?

1
  • You have a function : function(resp) which is changing your this the one you expect from the class. Use arrow function. Commented Apr 3, 2017 at 13:42

1 Answer 1

8

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

Use instead arrow functions:

then((resp) => {
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.