I have an Angular based application that is making a RESTful request to a server whose response is a JSON stream that represents a list of objects of the following type:
export interface Personal {
theAddress: string;
theCity: string;
theState: String;
theCountry: string;
emailAddress: string;
}
The code within my component uses an HttpClient GET request to get data to place into an Observable:
people$: Observable<Personal[]>;
...
ngOnInit() {
this.people$ = this.http
.get<Personal[]>("/people/get")
.map(data => _.values(data))
.do(console.log);
}
For various reasons, I would like to extract the contents of the Observable and put them into an array of people objects. After reading various documentation on the Internet, I am aware that to extract the data received I need to somehow use a subscribe method on the Observable. Unfortunately, it is unclear to me exactly how to do this.
Can someone help with this? How does one extract the objects received by an Observable into an array?
You need to subscribe to the observable by calling .subscribe on it and pass a callback to subscribe. Inside this callback you will receive data from observable via callback parameters and than you can assign this data to local variable. see the code below
ngOnInit() {
this.people$ = this.http
.get<Personal[]>("/people/get")
.map(data => _.values(data))
.do(console.log)
.subscribe(data => this.someArray = data); // ==> see this line
}
The observable returned from the angular http.get are cold observable. They are not executed until you subscribe to them.
If you need the values in an array, you don't need people$ to be an observable. Just do this:
import 'rxjs/add/operator/map';
...
people: Personal[];
...
ngOnInit() {
// Let's get rid of lodash for the mapping thing
this.http.get<Map<string, Personal>>('/people/get')
.map(data => Object.keys(data).map(key => data[key]))
.subscribe((people: Personal[]) => this.people = people);
}
BTW you seem to be using an out-of-date rxjs library (previous to version 5.5). If you update it you'll have to use pipeable operators:
import {map} from 'rxjs/operators';
...
people: Personal[];
...
ngOnInit() {
// Let's get rid of lodash for the mapping thing
this.http.get<Map<string, Personal>>('/people/get')
.pipe(map(data => Object.keys(data).map(key => data[key])))
.subscribe((people: Personal[]) => this.people = people);
}
As an additional observation, as you're using a lodash function to convert objects to array. Apparently this.http.get<Personal[]> isn't really returning an array of Personal, but an object, so you'll probably have to write the get method like this (like I did on the above code):
this.http.get<{[id: string]: Personal}>
or
this.http.get<Map<string, Personal>>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With