2016-11-13 6 views
0

Google Gmail APIによるGmail接続でAngular2のコンポーネントを作成しようとしています。私はGmailの私のAngular2アプリからメールのリストが必要ですが、私はいつも同じ問題を抱えています(zone.js:140 Uncaught TypeError:未定義(...)のプロパティ 'loadGmailApi'を読むことができません)このエラーの原因handleAuthClickと、この方法の作業OK:#AUTHORIZEボタンボタン呼び出し方法について クリック:未定義のAngular2とGmail APIの 'loadGmailApi'プロパティを読み取ることができません

は、私は以下のコードを理解しています。 上記のメソッド呼び出しthis.handleAuthResultとコードのこの部分もOK動作しますが、それはthis.loadGmailApiを呼び出すとき、私はエラーを取得する:

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

私はこの内のthis.loadGmailApiを呼び出すことはできませんなぜ.handleAuthResultメソッド?

私のHTMLコード:

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

そして、TSファイル:

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); 
    } 
} 

答えて

0

おかげ@Dralacをあなたの助けと参照用How to access the correct this/context inside a callback?

に誰かが、私はこのビデオで見てお勧めします同様の問題がある場合:Understanding this in TypeScript

を最後に、私は専用のGmailApiServiceを作成しましたAngular2 TSサービスでのこの参照は

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); 
    } 
} 
0

それが別のコンテキストを持っているので、あなたはhandleAuthResult機能でthisを使用することはできません。あなたはここでそれについての詳細を確認することができます。How to access the correct `this` context inside a callback?

+0

ありがとうございました。最後に ''( '' => {'と' var self = this; ')を使ってコールバックの中に正しい' this'コンテキストを保持します。 –

関連する問題