我正在使用 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 毫秒的超时才能使用它,而且它很难看。
这段代码给了我以下错误:
ERROR TypeError: Cannot read property 'request' of undefined
请不要:
1-我还没有使用 npm/yarn 安装任何东西,我只是使用带有gapi var声明的脚本。
2 - 每次构建后,代码都可以正常工作,不会出现任何错误,并在第一次加载页面时填充我的表单,然后在一次刷新后,每次都会失败。
如何告诉 Angular 在启动时在所有组件之前加载 client.js ?
谢谢!
最佳答案
感谢@ADarnal,我终于通过阅读此主题找到了解决方案:
How to pass parameters rendered from backend to angular2 bootstrap method
我遵循了computeiro的答案中描述的相同流程。
我的“BackendRequestClass”类的等效项是 GapiService。
在此 Gapi 服务中,load 方法允许我在执行任何其他调用之前加载 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']
});
}
最后;在我的组件中,我注入(inject)了这个gapiService,并且我能够在组件初始化中使用client.request!
ngOnInit() {
this.gapiService
.getUserById(5066549580791808)
.then(
...
});
关于javascript - 加载gapi后加载Angular 5组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50721904/