2016-11-13 2 views
0

Google Gmail API로 Gmail 연결로 Angular2 용 구성 요소를 만들려고합니다. 내 Gmail에서 내 이메일 Angular2 애플 리케이션이 필요하지만, 나는 항상 같은 문제 (zone.js : 140 Uncaught TypeError : 정의되지 않은 (...)의 속성 'loadGmailApi'를 읽을 수 없음) 이해가 안되네요. 이 오류의 원인 handleAuthClick이 방법은 작업 OK : # 권한 부여 버튼 버튼 호출 방법에 클릭 :정의되지 않은 Angular2 및 Gmail API의 'loadGmailApi'속성을 읽을 수 없습니다.

나는 아래의 코드를 이해합니다.

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

왜이 내부 this.loadGmailApi 호출 할 수 없습니다 : 그것은 this.loadGmailApi를 호출 할 때 위의 메서드 호출 this.handleAuthResult 코드의이 부분은 내가 오류 확인을 작동하지만 .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' 컨텍스트를 유지합니다. –

관련 문제