How To Cast Observable Response To Local Object
In current Angular 6 application there is a subscribe to observable (response from RESTful service) this.activatedRoute.data.subscribe(({bag}) => { console.log(bag); t
Solution 1:
I suspect that this object is a ResponseEntity from Spring and not a HttpResponse from angular. The tell is statusCodeValue
which is not a property of angular's HttpResponse. If you are serializing spring ResponseEntitys and sending them as the response AND observing the response body
(indirectly or directly—which all appear true here), you need to create a similar interface in the front-end and use it in your service:
interface ResponseEntity<T> {
headers: { [headerName: string]: string },
body: T,
statusCode: "OK" | "SERVER_ERROR" | "BAD_REQUEST", //etcstatusCodeValue: "200" | "500" | "400" | "404"//etc
}
Sample Service
import { ResponseEntity } from"./dir/dir/file";
classBagService {
constructor(http: HttpClient) {}
find(id: string): Observable<Bag> {
returnthis.http.get<ResponseEntity<Bag>>(`/bag/${id}`).pipe(
map(resp => resp.body)
);
}
}
I hope this helps!
Solution 2:
I would sugest that you don't subscribe in the TypeScript and use the async pipe in the view
bag$ = this.activatedRoute.data.pipe(
map(res => res.body) // This will map your data to extract the body
);
in your TypeScript and in your view
<div *ngIf="bag$ | async as bag">
{{bag | json}}
</div>
That is what the async pipe is for and you don't have to worry about managing subscriptions.
Solution 3:
If the response in json format then you can write directly
this.http.method(url, option).pipe(map((this.handelResponse))
handelResponse(res: Response){
data = res.json;
// do whatever you wantreturndata// or return your object
}
Post a Comment for "How To Cast Observable Response To Local Object"