I use to do this in Angular 4/5:
import { Http, Headers } from "@angular/http"
public listTemplates(): Observable<EmailTemplate[]> {
let url = `${this.apiUrl}/templates`
this.http.get(url).map(
response => this.parseTemplates(response.body)),
error => new ErrorObservable(error)
)
}
Now, with Angular 8, I'm trying to use the HttpClient
class:
import { HttpClient, HttpResponse } from "@angular/common/http"
import { Observable } from "rxjs"
import { ErrorObservable } from "rxjs/observable/ErrorObservable";
public listTemplates(): Observable<EmailTemplate[]> {
let url = `${this.apiUrl}/templates`
return this.http.get(url)
.pipe( // ??
map( //??
response => this.parseTemplates(response.body)), // ?? HttpResponse
error => new ErrorObservable(error)
)
)
}
map
does not exist anymorepipe
, how to use it?HttpResponse
does not have a json
method anymoreI think I should be able to use .get
to obtain an any
object that will be my JSON object (as .get
documentation says), but how?
How can I use pipe
or map
(or both) to manage JSON object returned by the .get
with a custom parsing and return a collection or an Observable of a collection?
[Solution]
import { HttpClient, HttpResponse } from "@angular/common/http"
import { Observable } from "rxjs"
import { ErrorObservable } from "rxjs/observable/ErrorObservable"
import { map } from 'rxjs/operators'
public listTemplates(): Observable<EmailTemplate[]> {
let url = `${this.apiUrl}/templates`
return this.http.get(url).pipe(
map(
data => this.parseTemplates(data),
error => new ErrorObservable(error)
)
)
}
I still do not know how to get the HttpResponse for the cases where I need to check the HTTP status or some HTTP header. I understand that what get
is returning is driven by the type returned by the function (because of the pipe
call).
I tried to use get<HttpResponse<any>>
but didn't worked.
Here is a working example similar to your use case. I get an array of JSON objects and convert/parse them to an array of my data interface (GeneratorOffer):
getGeneratorOffers(): Observable<GeneratorOffer[]> {
return this.http.get<any[]>('shop/offers').pipe(
map(
jsonArray =>
jsonArray.map(jsonOffer => {
try {
return buildGeneratorOffer(jsonOffer);
} catch (error) {
console.error(`Offer could not be parsed: ${error}, json: ${JSON.stringify(jsonOffer)}`);
}
}),
catchError(err => {
console.error('Offers could not be loaded', err);
return of([]);
})
)
);
}
The actual parsing for each JSON object happens in buildGeneratorOffer()
.