Home > Mobile >  How to get the multiple observables from one observable of API Response in Angular
How to get the multiple observables from one observable of API Response in Angular

Time:04-27

I am trying to get the data from the API response it's having some properties the thing is i need to map and treat each property as observable because i am sending those observables to the child component to bind the data the following one is a samle response so i need to take the data part from there and i need to have a data1 as one obsarvable data2 as another one and so on

     {
      PageDetails: 'pagedetails',
      data: {
       data1: [],
       data2: [],
       data3: [],
       data4: []
      }
     }
    

CodePudding user response:

You might be able to use this, depending on your use case:

const newObservable$ = Observable.of(data1);

This will behave as follows:

Returns an Observable instance that synchronously delivers the values provided as arguments.

So every value in your array will be emitted as a value through this observable. So I assume you would create an observable for each of your data arrays in this way, and pass those observables on to other functions. Note that these observables will not emit the array as the value, but will emit the values in the array.

More info here

CodePudding user response:

Instead of passing to your children components the data as observables, you could pass the actual values.

For example:

Parent

<ng-container *ngIf="result$ | async as result">
  <child1 [data1]="result.data1"></child1>
  <child2 [data2]="result.data2"></child2>
  <child3 [data3]="result.data3"></child3>
  <child4 [data4]="result.data4"></child4>
</ng-container>

ts

...
export class ParentComponent implements OnInit() {
   result$!: Observable<any>; // create your own interface

   constructor(private service: YourService) {}
  
   ngOnInit() {
     this.result$ = this.service.getMyResponse().pipe(
       map((response) => response.data)
     );
   }
}

Child1

...
export class Child1Component {
  @Input() data1!: any[];

}

With this approach, all your child components will be updated/react to any possible changes been made from your parent component.

  • Related