Hi I am developing web application in Angular 5. I am developing tree structure in Angular 5. I am making http get call to get child nodes. I am able to get child nodes but api is going to infinite loop. It never stops. Below is my implementation.
getChildren(node: any) {
return new Promise((resolve, reject) => {
this.nodeservice.GetNodes().subscribe((data: any) => {
const newNodes = data.map((c) => Object.assign({}, c));
setTimeout(() => resolve(newNodes), 1000);
});
});
}
Below is my service call.
public GetNodes() {
return this.http.get('http://localhost:4200/assets/jsonresponse.json');
}
May I know what I am missing in the above code? Any help would be appreciated. Thank you.
No need to return a new promise from your subscription, just have your service Observable become a promise using .toPromise()
So in your service, "nodeService" rather, getNodes() would use the httpClient or http from angular to create an Observable and then you promisfy that.
HttpClient:
this.http.get().toPromise()
Http:
return this.http.get(this.data, v)
.toPromise()
.then(response => response.json())
.catch(this.handleError);
and then in your component or wheverever you subscribe, you are getting a promise so use then(). Don't forget to change any method sigs return value to Promise if you are using toPromise().
ex:
getNodes(): Promise<any>
Your Component: Remove the new promise, and instead of subscribe use then()
getChildren(node: any) {
this.nodeservice.GetNodes().then((data: any) => {
const newNodes = data.map((c) => Object.assign({}, c));
setTimeout(() => resolve(newNodes), 1000);
});
}
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.