无法读取未定义的Angular2和Gmail API的属性'loadGmailApi' [英] Cannot read property 'loadGmailApi' of undefine Angular2 and Gmail API
问题描述
我尝试使用Google Gmail API通过Gmail连接为Angular2创建组件。我需要一个Gmail的电子邮件列表,我的Angular2应用程序,但我得到所有时间相同的问题(zone.js:140 Uncaught TypeError:无法读取未定义(...)属性'loadGmailApi'),我不明白
我了解以下代码:
点击#authorize-button 按钮调用方法: handleAuthClick ,并且此方法工作正常。
上面的方法调用 this.handleAuthResult 和这部分代码也可以正常工作,但是当它调用 this.loadGmailApi 时,我得到错误:
zone.js:140未捕获的类型错误:无法读取未定义的属性'loadGmailApi'(...)
为什么我不能在this.handleAuthResult方法中调用this.loadGmailApi?
我的HTML代码:
< div id =authorize -div>
< span>授权访问Gmail API< / span>
<! - 用户点击以启动授权序列的按钮 - >
< button id =authorize-button(click)=handleAuthClick(event)>
授权
< / button>
< / div>
< pre id =output>< / pre>
和TS文件:
从'@ angular / core'导入{Component,OnInit};
从@ angular / router导入{Router};
$ b @Component({
selector:'gmail-app',
templateUrl:'/app/gmail/gmail.component.html'
})
导出类GmailComponent实现了OnInit {
//您的客户ID可以从Google
//开发者控制台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'];
的构造函数(){
}
ngOnInit(){
}
/ **
*的检查当前用户是否授权此应用程序。
* /
checkAuth(){
console.log(checkAuth);
gapi.auth.authorize(
{
'client_id':this.CLIENT_ID,
'scope':this.SCOPES.join(''),
'立即:真
},this.handleAuthResult);
}
/ **
*响应用户点击授权按钮启动授权流程。
*
* @param {Event}事件按钮单击事件。
* /
handleAuthClick(event){
console.log(handleAuthClick);
gapi.auth.authorize(
{
client_id:this.CLIENT_ID,
scope:this.SCOPES,
immediate:false
},this。 handleAuthResult);
返回false;
}
/ **
*处理来自授权服务器的响应。
*
* @param {Object} authResult授权结果。
* /
handleAuthResult(authResult){
console.log(handleAuthResult);
var authorizeDiv = document.getElementById('authorize-div');
if(authResult&&!authResult.error){
//隐藏认证用户界面,然后加载客户端库。
authorizeDiv.style.display ='none';
this.loadGmailApi;
} else {
//显示auth UI,允许用户通过
// //点击授权按钮来启动授权。
authorizeDiv.style.display ='inline';
}
}
/ **
*加载Gmail API客户端库。一旦客户端库
*被加载,列出标签。
* /
loadGmailApi(){
console.log(loadGmailApi);
gapi.client.load('gmail','v1',this.listLabels);
}
/ **
*打印授权用户收件箱中的所有标签。如果没有找到标签
*,则打印相应的信息。
* /
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&& label.length> 0){
// for(private i = 0; i< labels.length; i ++){
// var label = labels [i ];
// this.appendPre(label.name)
//}
this.appendPre('Foudnd - Kris disabled it');
} else {
this.appendPre('No Labels found。');
}
});
}
/ **
*将pre元素附加到包含给定消息
*的文本节点的主体中。
*
* @param {string}消息要放置在pre元素中的文本。
* /
appendPre(message){
console.log(appendPre);
var pre = document.getElementById('output');
var textContent = document.createTextNode(message +'\\\
');
pre.appendChild(textContent);
$ div $解析方案
谢谢@Dralac为您提供帮助,并参考了如何在回调中访问正确的这个
/ context?
如果有人有类似的问题,我建议查看此视频:在TypeScript中了解此内容
最后,我创建了专用的GmailApiService,并在Angular2 TS服务中引用了此引用:
import {Injectable} from @角/芯;
@Injectable()
导出类GmailApiService {
公共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);
返回false;
};
handleAuthResult =(authResult)=> {
var authorizeDiv = document.getElementById('authorize-div');
if(authResult&&!authResult.error){
//隐藏认证用户界面,然后加载客户端库。
authorizeDiv.style.display ='none';
this.loadGmailApi();
} else {
//显示auth UI,允许用户通过
// //点击授权按钮来启动授权。
authorizeDiv.style.display ='inline';
}
};
loadGmailApi =()=> {
gapi.client.load('gmail','v1',this.listLabels);
};
listLabels =()=> {
var request = gapi.client.gmail.users.labels.list({$ b $'userId':'me'
});
var self = this;
request.execute(function(resp){
var labels = resp.labels;
self.appendPre('Labels:');
if(labels&& label.length> 0){
for(var i = 0; i< labels.length; i ++){
var label = labels [i];
self.appendPre(label.name)
}
}其他{
self.appendPre( '未发现标签。');
}
});
};
appendPre =(message)=> {
var pre = document.getElementById('output');
var textContent = document.createTextNode(message +'\\\
');
pre.appendChild(textContent);
}
}
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);
}
}
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);
}
}
这篇关于无法读取未定义的Angular2和Gmail API的属性'loadGmailApi'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!