Reputation: 3973
I am reading about Promise and Observable and I am not sure if my code is valid for angular2+
I am using Promise with new http client
return new Promise((resolve) => {
this.http
.get('http://x.x.com/api/x/' + x + '/' + x + '/' + x + '', {
headers: this.authenticationService.getAuthorizationHeader()
})
.subscribe(
(data: any) => {
resolve(data.map((row) => {
return new Candlestick(row.time, row.open, row.high, row.low, row.close, row.volume)
}));
},
(error: HttpErrorResponse) => {
if (error.error instanceof Error) {
console.log('An error occurred:', error.error.message);
} else {
console.log(`Backend returned code ${error.status}, body was: ${error.error}`);
}
return resolve();
});
});
Is this ok or bad example?
Upvotes: 2
Views: 46
Reputation: 19514
Code looks okey but if your purpose is to use observable then you can use toPromise
this.http
.get('http://x.x.com/api/x/' + x + '/' + x + '/' + x + '', {
headers: this.authenticationService.getAuthorizationHeader()
})
.toPromise()
.then()
Also in your code you are doing resolve() on error which is wrong to me, i would better call reject.
Your code would make more sense lets say if you want to do retries or any other cool things, but if you need Promise then use toPromise.
Upvotes: 3