I am calling a javascript function in an angular component. I included the JS file in " angular.json " and it works fine. The JS function do a http GET request and return data. The problem is I couldn't tell Angular to wait for the JS response to then fetch data.
This is my JS function :
function getDataJsFunct(id) {
var params = {id:id}
apiClient.getById(params) { console.log('data from JS', result);
return result;
}
}
And this is my TS files : In 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();
}
});
}
}
In component.service.ts
@Injectable()
export class ComponentService {
constructor(private serviceProvider: ApiServices) {}
getDataFromProvider(id) {
return this.serviceProvider.getAction(id);
}
}
In component.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);
});
}
The program is crashing at " getDataFromProvider(id). ***then***
((data " because getDataFromProvided(id) is undefined. I suppose that I need a promise to tell Angular to wait for JS response then continu executing. How and where should I do that please ?
I think your issue is that you are not passing the correct variable name in the service.
Currently, you have:
@Injectable()
export class ComponentService {
constructor(private serviceProvider: ApiServices) {}
getDataFromProvider(urlApi) {
return this.serviceProvider.getAction(id);
}
}
You are calling this.serviceProvider.getAction(id)
with the variable id
when the parameter of the function is urlApi
.
You should change urlApi
for id
:
@Injectable()
export class ComponentService {
constructor(private serviceProvider: ApiServices) {}
getDataFromProvider(id) {
return this.serviceProvider.getAction(id);
}
}
Can you check if that was the issue?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.