1

在这个例子中,我创建的 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 的值。” ...“无论您使用多少级嵌套,箭头函数都将始终具有正确的上下文。”

因此,我认为不是创建bindingandselfthatand ,而是更干净的使用wherever=>

让我感到困惑的另一件事是谷歌 api 要求没有参数的回调。

所以如果你尝试使用 const that = this; gapi.load('client:auth2', this.start(that) );

它会抱怨。

但是使用 gapi.load('client:auth2', () => this.start() );我没有传递参数。

这对很多人来说可能很简单,但由于我正在学习,我会尽量让其他也在学习的人变得简单。

感谢大家。

4

2 回答 2

1

this始终是调用该方法的对象。但是,当将方法传递给 then() 时,您并没有调用它!该方法将存储在某个地方并稍后从那里调用。

如果要保留它,则需要先保留它:

var that = this;
// ...
.then(function() { that.method() })
于 2018-03-16T07:00:27.733 回答
1

this在这里,您通过调用失去了范围:

gapi.load('client:auth2', this.youtubePromise);

将上面的代码更改为:

gapi.load('client:auth2', () => this.youtubePromise()); // ES6 Way
// OR
gapi.load('client:auth2', this.youtubePromise.bind(this)); // Traditional old way of doing

工作演示

于 2018-03-16T07:08:00.240 回答