如何在Angular promise中获得javascript响应



我正在角度组件中调用一个javascript函数。我在"angular.json"中包含了JS文件,它运行良好。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("处崩溃,因为getDataFromProvidered(id(未定义。我想我需要一个承诺来告诉Angular等待JS响应,然后继续执行。请问我该怎么做,在哪里做?

我认为您的问题是没有在服务中传递正确的变量名。

目前,您有:

@Injectable()
export class ComponentService {
constructor(private serviceProvider: ApiServices) {}
getDataFromProvider(urlApi) {
return this.serviceProvider.getAction(id);
}
}

当函数的参数为urlApi时,您正在使用变量id调用this.serviceProvider.getAction(id)

您应该将urlApi更改为id:

@Injectable()
export class ComponentService {
constructor(private serviceProvider: ApiServices) {}
getDataFromProvider(id) {
return this.serviceProvider.getAction(id);
}
}

你能检查一下是不是这个问题吗?

最新更新