【发布时间】: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