Requests as Promises
The observable returned by Angular http client can be converted it into a promise.
We recommend using observables over promises. By converting to a promise you will be lose the ability to cancel a request and the ability to chain RxJS operators.
1
import { HttpClient } from '@angular/http/common';
2
import { Injectable } from '@angular/core';
3
import { map } from 'rxjs/operators';
4
5
@Injectable()
6
export class SearchService {
7
8
constructor(private http: HttpClient) {}
9
10
search(term: string) {
11
return this.http.pipe(
12
get(`https://api.spotify.com/v1/search?q=${term}&type=artist`),
13
map((response) => response.json())
14
).toPromise();
15
}
16
}
Copied!
We would then consume it as a regular promise in the component.
1
@Component({ /* ... */ })
2
export class AppComponent {
3
/* ... */
4
5
search() {
6
this.searchService.search(this.searchField.value)
7
.then((result) => {
8
this.result = result.artists.items;
9
})
10
.catch((error) => console.error(error));
11
}
12
}
Copied!
Last modified 3mo ago
Copy link