【问题标题】:gapi.client.youtube is undefined in angular appgapi.client.youtube 在 Angular 应用程序中未定义
【发布时间】:2022-04-20 19:14:31
【问题描述】:

注意:我知道该主题看起来与其他问题相似,但有所不同

我有调用 Google API (gapi) 的 Angular 应用程序。

我有调用 gmail api、calendar api 和 youtube api 的函数。

这里我有两个问题:

问题1:为什么youtube在这里无法识别? 虽然我已经安装了所有类型:

问题2:运行应用时,gmail api和calendar api调用正常,但是youtube api调用抛出youtube未定义的错误?

getMessages() {
    return gapi.client.gmail.users.messages.list({ userId: 'me', labelIds: ['INBOX', 'UNREAD'] }).then();
}
getEvents() {
    return gapi.client.calendar.calendarList.list().then();
}

getChannels() {
    return gapi.client.youtube.channels.list({'part': 'snippet', 'mine': 'true'}).then();
}

由于某些原因在 getChannels() 函数中出现错误

Uncaught TypeError: Cannot read property 'channels' of **undefined**

其中 gapi.client.youtube 未定义。

gapi 已定义,客户端也已定义,但 youtube 未定义。

感谢任何帮助。如您所见,这些api的调用方式没有区别,相同的签名,不明白为什么youtube未定义。

这是调试模式下的截图

【问题讨论】:

标签: angular google-api-js-client


【解决方案1】:

答案 1:

检查@types/gapi.client.youtube,正确的应该是(至少是类型定义中定义的):

gapi.client.channels.list(null).then()

更新 正如 cmets 中所讨论的,我也认为类型定义是错误的,你应该在你的项目中扩展它(直到定义被修复)

答案 2: 或许this answer对你有帮助

【讨论】:

  • 根据文档developers.google.com/youtube/v3/guides/auth/… 它应该是'gapi.client.youtube.channels.list',否则它也不起作用。
  • 可能是类型定义错误?最后一次提交来自 2019 年
  • youtube 被定义为 gapi.client 的命名空间,与 @types/gapi.client.calendar 中定义的日历或 @types/gapi.client.gmail 中定义的 gmail 完全相同
  • 我知道这个主题看起来与其他问题相似,但又有所不同
  • @types/gapi.client.youtube 的定义方式与 @types/gapi.client.calendar 不同。查看youtube 命名空间的末尾,没有常量,而calendar 命名空间的末尾我们确实有它
【解决方案2】:

我相信 gapi 不适合与 node 或 Angular 一起使用。试试Google APIs Node.js Client

编辑:不是独立的,但这里有一个带有更新的related threadinstructions

【讨论】:

  • 这个线程与我所说的无关。我什至不知道他们使用的是什么库。没有像import { google } 这样的东西,或者他们在纯javascript的原始gapi中谈论的其他内容。我正在使用原始的 Google API (gapi) for javascript 没有问题,一切正常。
  • 如果一切正常,您就不会在这里。我把这个留在这里,以防有人偶然发现这个,这样他们就可以有选择,如果他们愿意尝试替代方案。正如我已经说过的,我认为 gapi 不适合 Node 和 Webpack 环境。
  • 至于他们使用的是什么库,就像gapi是Google API Client Library for JavaScript一样,我在答案中链接的googleapis库是Node.js client library for using Google APIs。是的,它是官方的,正如它在this guide 中的使用所证明的那样
【解决方案3】:

在使用 gapi.client.youtube 之前,您必须调用 init 函数:

gapi.load('client', () => {
  gapi.client.init({
    apiKey: *****,
    clientId: *****,
    discoveryDocs: *****,
    scope: *****,
  });
});

然后在您的 gapi.client.youtube.channels.list() 请求中,您应该使用它发送令牌:

gapi.client.youtube.channels
    .list({
        mine: true,
        part: 'statistics',
        access_token: //SAVED-TOKEN,
    })
    .then(res => {
        console.log('channels', res);
    });

【讨论】:

    猜你喜欢
    • 2014-08-26
    • 1970-01-01
    • 2017-07-12
    • 2021-08-23
    • 2017-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-15
    相关资源
    最近更新 更多