【问题标题】:Load Angular 5 component after gapi has been loaded加载 gapi 后加载 Angular 5 组件
【发布时间】:2018-11-16 05:28:38
【问题描述】:

我正在使用 CLI 编写一个 Angular 5 应用程序。 我正在使用 gapi 检索用户数据以填充表单。

客户端脚本包含在 index.html 文件中:

<head>
  <meta charset="utf-8">
  <script src="https://apis.google.com/js/client.js"></script>
  ...
</head>

这是我的调用组件:

userProfileModel: UserProfileModel = new UserProfileModel();

ngOnInit() {
  this.form = this.toFormGroup();
  this.onFormChanges();

  this.userService
      .getUserById(this.userId)
      .then(usr => {
        this.mapModel(usr.result['profile']);
      })
      .then(() => {
        this.form.patchValue(this.userProfileModel);
      });
}

还有userService的方法:

declare var gapi: any;

export class UserService {

  getUserById(id: number) {
    return gapi.client.request({
      method: 'GET',
      'path': this.constants['endpoint_user_getbyid'] + '/' + id,
      'root': this.constants['api_url']
    });
  }
  ...
}

问题是,gapi 似乎没有在我的组件完成加载后立即初始化:我必须设置一个 >500 毫秒的超时才能使用它,这很丑。

这段代码给了我以下错误:

错误类型错误:无法读取未定义的属性“请求”

请不要:

1- 我没有使用 npm / yarn 安装任何东西,我只是使用带有 gapi var 声明的脚本。
2 - 每次构建后,代码都可以正常工作,并在第一次加载页面时填充我的表单,然后在刷新一次后,每次都会失败。

如何告诉 Angular 在启动时在所有组件之前加载 client.js?

谢谢!

【问题讨论】:

标签: javascript angular client load google-api-js-client


【解决方案1】:

感谢@ADarnal,我终于通过阅读此主题找到了解决方案:

How to pass parameters rendered from backend to angular2 bootstrap method

我遵循了 computeiro 的回答中描述的完全相同的过程。
我等效的“BackendRequestClass”类是 GapiService。

在这个 Gapi 服务中,加载方法允许我在执行任何其他调用之前加载 gapi:

/* GapiService */

loadGapi() {
  return new Promise((resolve, reject) => {
    gapi.load('client', () => {
      gapi.client.init({apiKey: 'AIzaSyD5Gl9...'}).then(() => {            
        resolve(gapi.client);
      })
    });
  });
}

// Method used in any component
getUserById(id: number) {
  return gapi.client.request({
    method: 'GET',
    'path': this.constants['endpoint_user_getbyid'] + '/' + id,
    'root': this.constants['api_url']
  });
}

最后;在我的组件中,我注入了这个 gapiService,我可以在组件初始化时使用 client.request !

ngOnInit() {
  this.gapiService
      .getUserById(5066549580791808)
      .then(
        ...
  });

【讨论】:

    猜你喜欢
    • 2018-08-12
    • 2017-09-30
    • 2019-02-06
    • 2018-08-13
    • 1970-01-01
    • 2018-08-12
    • 2019-10-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多