RxJS Refactor nested map instruction

I have a service that uses @angular/httpto load data from an API. I want to create a projection of the extracted data for mine Componentsusing this data.

So I wrote the following code:

getById(id: string) {
  return this.http
    .get(`https://my-api.io/${id}`)
    .map(response => response.json())
    .map(contracts =>
      contracts.map(contract =>        # <- Nested map
        new Contract(
          contract['id'],
          contract['description']
        )
      )
    );
}

On line 6th , I have a nested map-Statement that reduces the readability of my code.

Question

Can i do better? Is there an operator in RxJS that I can use instead of creating this type of nesting?

Thanks in advance!

+4
source share
3 answers

flatMap/selectMany, . RxJS.map() . , RxJS.toArray() , :

const stream = $http('http://jsonplaceholder.typicode.com/posts')
 .map(res => res.data)
 .flatMap(posts => posts)
 .map(post => Object.assign({}, post, { status: false }))
 .toArray();

. : http://jsbin.com/vigizihiwu/1/edit?js,console

: ? , :

const stream = $http('http://jsonplaceholder.typicode.com/posts')
 .map(res => res.data);

stream.subscribe(res => {
  const posts = res.map(post => Object.assign({}, post, { status: false }));
  console.log(posts);
});
+3

@Alexander T.. , map -Statement: http://jsbin.com/hududiq/1/edit?js,console

:

getByAccountId(id: string) {
  return this.http
    .get(`http://my-api.io/${id}`)
    .map(contractsData => contractsData.json())
    .concatAll()
    .map(contract => Observable.of(new Contract(
                                    contract['id'],
                                    contract['description'])))
    .combineAll();
}
+2

.

map() ( ), map(), forEach() :

new Observable.of(testData)
  .map(contractsData => {
    var objects = [];
    JSON.parse(contractsData).forEach(o => objects.push(new Contract(o['id'], o['description'])));
    return objects;
  })
  .subscribe(val => console.log(val));

, .

-: http://plnkr.co/edit/NQgRVSCQGgPvTkPPGz7O ( , , ).

map(), :

new Observable.of(testData)
  .map(contractsData => JSON.parse(contractsData).map(o => new Contract(o['id'], o['description'])))
  .subscribe(val => console.log(val));

Btw, all statements ending in *allwork with a higher order of Observables (aka Observables emitting other Observables), and I was surprised that your code works because you are passing a regular array .concatAll()instead of Observable. This turned out to be an undocumented feature .concatAll()thanks to its extension . According to the documentation, this should not work.

+1
source

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


All Articles