0

I try to create component for Angular2 with Gmail connection by Google Gmail API. I need a list of e-mail from Gmail im my Angular2 apps, but I get all times the same problem (zone.js:140 Uncaught TypeError: Cannot read property 'loadGmailApi' of undefined(…)) and I don't understand the cause of this error.

I understand the code below: Click on #authorize-button button call method: handleAuthClick and this method work OK. The above method call this.handleAuthResult and this part of code also work OK, but when it call this.loadGmailApi I get error:

zone.js:140 Uncaught TypeError: Cannot read property 'loadGmailApi' of undefined(…)

Why I can't call this.loadGmailApi inside this.handleAuthResult method?

My HTML code:

<div id="authorize-div">
    <span>Authorize access to Gmail API</span>
    <!--Button for the user to click to initiate auth sequence -->
    <button id="authorize-button" (click)="handleAuthClick(event)">
        Authorize
    </button>
</div>
<pre id="output"></pre>

And TS files:

import {Component, OnInit} from '@angular/core';
import {Router} from "@angular/router";


@Component({
    selector: 'gmail-app',
    templateUrl: '/app/gmail/gmail.component.html'
})

export class GmailComponent implements OnInit{
    // Your Client ID can be retrieved from your project in the Google
    // Developer Console, https://console.developers.google.com
    public CLIENT_ID:string = 'GOOGLE_API_ID_STRING.apps.googleusercontent.com';
    public SCOPES:Array<string> = ['https://www.googleapis.com/auth/gmail.readonly'];

    constructor(){
    }

    ngOnInit(){
    }

    /**
     * Check if current user has authorized this application.
     */
    checkAuth() {
        console.log("checkAuth");
        gapi.auth.authorize(
            {
                'client_id': this.CLIENT_ID,
                'scope': this.SCOPES.join(' '),
                'immediate': true
            }, this.handleAuthResult);
    }

    /**
     * Initiate auth flow in response to user clicking authorize button.
     *
     * @param {Event} event Button click event.
     */
    handleAuthClick(event) {
        console.log("handleAuthClick");
        gapi.auth.authorize(
            {
                client_id: this.CLIENT_ID,
                scope: this.SCOPES,
                immediate: false
            }, this.handleAuthResult);
        return false;
    }

    /**
     * Handle response from authorization server.
     *
     * @param {Object} authResult Authorization result.
     */
    handleAuthResult(authResult) {
        console.log("handleAuthResult");
        var authorizeDiv = document.getElementById('authorize-div');
        if (authResult && !authResult.error) {
            // Hide auth UI, then load client library.
            authorizeDiv.style.display = 'none';
            this.loadGmailApi;
        } else {
            // Show auth UI, allowing the user to initiate authorization by
            // clicking authorize button.
            authorizeDiv.style.display = 'inline';
        }
    }

        /**
         * Load Gmail API client library. List labels once client library
         * is loaded.
         */

    loadGmailApi() {
        console.log("loadGmailApi");
        gapi.client.load('gmail', 'v1', this.listLabels);
    }

        /**
         * Print all Labels in the authorized user's inbox. If no labels
         * are found an appropriate message is printed.
         */
    listLabels() {
        console.log("listLabels");
        var request = gapi.client.gmail.users.labels.list({
            'userId': 'me'
        });

        request.execute(function(resp) {
            var labels = resp.labels;
            this.appendPre('Labels:');

            if (labels && labels.length > 0) {
                // for (private i = 0; i < labels.length; i++) {
                //     var label = labels[i];
                //     this.appendPre(label.name)
                // }
                this.appendPre('Labels foudnd - Kris disabled it');
            } else {
                this.appendPre('No Labels found.');
            }
        });
    }

        /**
         * Append a pre element to the body containing the given message
         * as its text node.
         *
         * @param {string} message Text to be placed in pre element.
         */
    appendPre(message) {
        console.log("appendPre");
        var pre = document.getElementById('output');
        var textContent = document.createTextNode(message + '\n');
        pre.appendChild(textContent);
    }
}
kris_IV
  • 2,396
  • 21
  • 42

2 Answers2

0

You can't use this in handleAuthResult function since it has different context. You can check more about it here: How to access the correct `this` context inside a callback?

Community
  • 1
  • 1
Dralac
  • 199
  • 2
  • 9
  • Thanks for your help. Finally I use `= () => {` and `var self = this;` to keep correct `this` context inside a callback. – kris_IV Nov 20 '16 at 15:01
0

Thanks @Dralac for your help and references to How to access the correct this / context inside a callback?

If somebody have similar problems I recommend to look on this video: Understanding this in TypeScript

Finally I created dedicated GmailApiService with this references in Angular2 TS service:

import {Injectable} from "@angular/core";

@Injectable()
export class GmailApiService {
    public CLIENT_ID = '525210254723-5a80ara29lspplau6khbttb0fbacnppr.apps.googleusercontent.com';
    public SCOPES = ['https://www.googleapis.com/auth/gmail.readonly'];

    checkAuthAuto = () => {
        gapi.auth.authorize(
            {
                'client_id': this.CLIENT_ID,
                'scope': this.SCOPES.join(' '),
                'immediate': true
            }, this.handleAuthResult);
    };

    checkAuthManual = () => {
        gapi.auth.authorize(
            {
                'client_id': this.CLIENT_ID,
                'scope': this.SCOPES.join(' '),
                'immediate': false
            }, this.handleAuthResult);
        return false;
    };


    handleAuthResult = (authResult) => {
        var authorizeDiv = document.getElementById('authorize-div');

        if (authResult && !authResult.error) {
            // Hide auth UI, then load client library.
            authorizeDiv.style.display = 'none';
            this.loadGmailApi();
        } else {
            // Show auth UI, allowing the user to initiate authorization by
            // clicking authorize button.
            authorizeDiv.style.display = 'inline';
        }
    };

    loadGmailApi = () => {
        gapi.client.load('gmail', 'v1', this.listLabels);
    };

    listLabels = () => {
        var request = gapi.client.gmail.users.labels.list({
            'userId': 'me'
        });
        var self = this;

        request.execute(function(resp) {
            var labels = resp.labels;
            self.appendPre('Labels:');

            if (labels && labels.length > 0) {
                for (var i = 0; i < labels.length; i++) {
                    var label = labels[i];
                    self.appendPre(label.name)
                }
            } else {
                self.appendPre('No Labels found.');
            }
        });
    };

    appendPre = (message) => {
        var pre = document.getElementById('output');
        var textContent = document.createTextNode(message + '\n');
        pre.appendChild(textContent);
    }
}
Community
  • 1
  • 1
kris_IV
  • 2,396
  • 21
  • 42