javascript - 如何在 Angular 承诺中获得 javascript 响应
问题描述
我在角度组件中调用 javascript 函数。我将 JS 文件包含在“angular.json”中,它工作正常。JS 函数执行 http GET 请求并返回数据。问题是我不能告诉 Angular 等待 JS 响应然后获取数据。
这是我的 JS 函数:
function getDataJsFunct(id) {
var params = {id:id}
apiClient.getById(params) { console.log('data from JS', result);
return result;
}
}
这是我的 TS 文件:在 api-services.ts
declare var getDataJsFunct: any;
export class ApiServices {
.
.
public getAction(id) {
return new Promise ( resolve => {
const data = getDataJsFunct(id);
if (data) {
console.log('result', data);
return resolve();
}
});
}
}
在 component.service.ts
@Injectable()
export class ComponentService {
constructor(private serviceProvider: ApiServices) {}
getDataFromProvider(id) {
return this.serviceProvider.getAction(id);
}
}
在组件.ts
ngOnInit() {
let id = '123456';
this.componentService.getDataFromProvider(id).then((data: any) => {
this.dataFromBd = data.Items[0];
},
error => {
console.log('Error in getting Data', error);
});
}
该程序在“ getDataFromProvider(id) 处崩溃。***then***
((data ”,因为 getDataFromProvided(id) 未定义。我想我需要一个承诺来告诉 Angular 等待 JS 响应然后继续执行。请问我应该如何以及在哪里这样做?
解决方案
我认为您的问题是您没有在服务中传递正确的变量名。
目前,您有:
@Injectable()
export class ComponentService {
constructor(private serviceProvider: ApiServices) {}
getDataFromProvider(urlApi) {
return this.serviceProvider.getAction(id);
}
}
当函数的参数为 时,您正在this.serviceProvider.getAction(id)
使用变量调用。id
urlApi
你应该urlApi
改变id
:
@Injectable()
export class ComponentService {
constructor(private serviceProvider: ApiServices) {}
getDataFromProvider(id) {
return this.serviceProvider.getAction(id);
}
}
你能检查一下是不是这个问题吗?
推荐阅读
- php - Laravel Worker 似乎并没有停止
- regex - 如何在正则表达式中定义可选后缀?
- mysql - mysql 从 2 个表中选择获取
- ruby-on-rails - Ruby on Rails - 枚举的显示名称
- c - 使用 fork() 时的奇怪输出
- c - mpi 在一个结构中发送/接收多个可变长度数组
- reactjs - 使用映射函数返回的 Jest 和 Enzyme 测试 React 组件
- excel - 如何遍历文件夹和子文件夹来打开文件?
- python - ipython qtconsole --colors=linux 不起作用
- cmake - 如何通过 cmake 中的接口库正确传播使用需求?