在这个例子中,我创建的 Promise 可以正常工作。
但是来自google api的承诺不起作用。
它说this.youtube
是未定义的
索引.html
<script src="https://apis.google.com/js/api.js"></script>
app.component.html
<button (click)="customClick()">custom Promise</button>
<hr>
<hello name="{{ youtube }}"></hello>
<button (click)="youtubeClick()">youtube Promise</button>
app.component.ts
import { Component } from '@angular/core';
import { } from '@types/gapi.client.youtube';
import { } from '@types/gapi.auth2';
export class AppComponent {
name = 'Angular 5';
youtube = 'youtube';
egPromise(){
return new Promise<void>((resolve, reject) => {
setTimeout(function(){
resolve();
}, 1000);
});
}
customPromise(){
this.egPromise().then( () => {
this.name = 'from .then angular 5'
});
}
customClick(){
this.customPromise();
}
/****************************************************/
youtubePromise(){
gapi.client.init({
apiKey: 'key',
clientId: 'id',
scope: "https://www.googleapis.com/auth/youtube.readonly",
discoveryDocs: [
"https://www.googleapis.com/discovery/v1/apis/youtube/v3/rest"
]
}).then(() => {
this.youtube = 'from .then youtube'
});
}
youtubeClick(){
gapi.load('client:auth2', this.youtubePromise);
}
编辑:解决方案/解释
在@vivek-doshi 的帮助下
我发现这篇文章搜索“绑定这个”
https://www.sitepoint.com/bind-javascripts-this-keyword-react/
正如帖子所解释的
“在你的代码中,这并不总是很清楚,尤其是在处理回调函数时,你无法控制其调用点。”
由于我正在使用谷歌 API,我无法控制该代码。
“这是因为当调用 promise 的回调时,函数的内部上下文发生了变化,并且 this 引用了错误的对象。”
加载库的函数使用回调函数,我什至没有想到第一个回调是问题所在。
因此,正如帖子所说,使用 ES2015 Fat Arrows 功能。
“他们总是在封闭范围内使用 this 的值。” ...“无论您使用多少级嵌套,箭头函数都将始终具有正确的上下文。”
因此,我认为不是创建binding
andself
和that
and ,而是更干净的使用wherever
=>
让我感到困惑的另一件事是谷歌 api 要求没有参数的回调。
所以如果你尝试使用
const that = this;
gapi.load('client:auth2', this.start(that) );
它会抱怨。
但是使用 gapi.load('client:auth2', () => this.start() );
我没有传递参数。
这对很多人来说可能很简单,但由于我正在学习,我会尽量让其他也在学习的人变得简单。
感谢大家。