In the service, I want to create a method that will simultaneously send two requests to the carved url (this.http.get ( ${url} ). The first request should return an array, and another object. And put the results in the created object under the appropriate names (obj .array, obj.object) which method should return. But the problem is that I don’t know how to return the data correctly, because each of the requests returns Observable. Please help, if possible with the code, I will be grateful for autumn.
|
1 answer
From an experienced developer I learned about such a thing as Observable.forkJoin() .
To use, you need to install Rx.js in the project, and then import to where the request is made ( import 'rxjs/add/observable/forkJoin' ) The arguments of this method will be queries, it returns an Observable array. It can be used in a separate method in the service, and then in the component through the Rx.js method .subscribe() process the data.
Example:
service.ts
getJsonArray(){ return Observable.forkJoin( this.http.get('website.com/cars.json'), this.http.get('website.com/boats.json') ); } component.ts
myCars: any[]; myBoats: any[]; constructor(private service: YourServiceName){} ngOnInit(){ this.service.getJsonArray().subscribe(data => { this.myCars = data[0]; this.myBoats = data[1]; }); } |