Angular 2 + rxjs - as a return stream of objects received using several subsequent HTTP requests

I have data classes

class Processor {
    frequency: number;
    error: booelan;
}

class Computer {
    name: string;
    processor: Processor[];
}

I am extracting it from the backend using json:

{
    "name": "Alfa Beta",
    "processors": [
        {
            "url": "ASD3-455R-FRTT-ASEW"
        },
        {
            "url": "AQW2-DFFFR-367K-MMKE"
        }
    ]
}

and one processor

{
    "url": "ASD3-455R-FRTT-ASEW",
    "frequency": 2200,
    working: true
}

I need to return the thread Computer, since I would like to request the status of the processors every minute. For a single returned instance, ComputerI need to send three HTTP requests with dependencies from each other. Of course, for this I will use the class of service. The only problem for me is how to create this thread, i.e. this.http.get(this.mainUrl)?

I found Reactive Programming, HTTP and Angular 2 and the chapter Executing a query with the result of the previous one, but it wasn’t Help.

+2
1

concatMap operator (, exitMap ReactiveX/rxjs 5 TypeScript).

, :

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/concatMap';
import 'rxjs/add/operator/do';

var urls = [
  'https://httpbin.org/get?1',
  'https://httpbin.org/get?2',
  'https://httpbin.org/get?3',
  'https://httpbin.org/get?4',
  'https://httpbin.org/get?5',
];     

Observable.from(this.urls)
  .concatMap(url => http.get(url))
  .subscribe(response => console.log(response.url))
;

:

https://httpbin.org/get?1
https://httpbin.org/get?2
https://httpbin.org/get?3
https://httpbin.org/get?4
https://httpbin.org/get?5

concatMap() ( URL ) Observable . Observable, . , http.get() Observable, Response, .

. plnkr: http://plnkr.co/edit/PJ7SpkNgBjZz2h4uvRpK?p=preview ( app.component.ts)

, ( ?), , , :

http.get('https://httpbin.org/get?1')
  .do(response => console.log('Process response', response.url))

  .concatMap(response => {
    console.log('Previous response', response.url, ' about to run /get?2')
    return http.get('https://httpbin.org/get?2')
  })
  .do(response => console.log('Process response', response.url))

  .concatMap(response => {
    console.log('Previous response', response.url, ' about to run /get?3')
    return http.get('https://httpbin.org/get?3')
  })

  .subscribe(response => console.log('Done', response.url))
;

:

Process response https://httpbin.org/get?1
Previous response https://httpbin.org/get?1  about to run /get?2
Process response https://httpbin.org/get?2
Previous response https://httpbin.org/get?2  about to run /get?3
Done https://httpbin.org/get?3

, concatMap(), Observable, , http.get(), do() operator , , ( concatMap()).

. plnkr: http://plnkr.co/edit/VFv09dTekK8av1Pu3a75?p=preview ( app.component.ts)

+2

Source: https://habr.com/ru/post/1656406/


All Articles