Reputation: 10345
When I make a GET call via HttpClient I want to pass back an array of the actual typed objects, vs. just a generic 'object', and so I tried to do this:
getExistingArsByLab(labId: number): Observable<EhsAssessmentAr[]> {
return this.http
.get<EhsAssessmentAr[]>(`${this.baseUrl}/ar?labId=${labId}`)
.pipe(
map(x => {
const ret = EhsAssessmentAr.fromJson(x);
ret.ar = this.sanitizer.sanitize(SecurityContext.HTML, ret.ar.replace(/\n/g, '<br/>'));
return ret;
})
)
}
That fromJson
method is declared to return the proper class, and I thought since I was sending this through map
that I'd get back an array. I'm REALLY new to RxJs so I'm sure I'm just doing something completely stupid there.
I'm getting theerror:
TS2322: Type 'Observable<EhsAssessmentAr>' is not assignable to type 'Observable<EhsAssessmentAr[]>`
Upvotes: 1
Views: 14325
Reputation: 2506
That is already the default behavior of Angular 7 HttpClient. So unless you need to do some extra processing of html or something like in your example, you just need the following:
getExistingArsByLab(labId: number): Observable<EhsAssessmentAr[]> {
return this.http
.get<EhsAssessmentAr[]>(`${this.baseUrl}/ar?labId=${labId}`)
}
Upvotes: 0
Reputation: 3051
You can strong type your mapping response and Check you are returning array not single element:
getExistingArsByLab(labId: number): Observable<EhsAssessmentAr[]> {
return this.http
.get<EhsAssessmentAr[]>(`${this.baseUrl}/ar?labId=${labId}`)
.pipe(
map((x:EhsAssessmentAr[]) => {
const ret = EhsAssessmentAr.fromJson(x);
ret.ar = this.sanitizer.sanitize(SecurityContext.HTML, ret.ar.replace(/\n/g, '<br/>'));
return ret;
})
)
}
Pro-tip 2: If you are changing return type for any reason you can use:
return <TypedArray[]> arrParsed["something"];
Pro-tip 3: Angular hates you feed it with html so you need to find some cool solution like when templating adding a replace of token to new line
Upvotes: 1