Home > Net >  Angular rxjs conditional get query
Angular rxjs conditional get query

Time:02-19

My json file contains several arrays, like below :


{
    A[]
    B[]
    C[]
    ...
}

My query looks like this :


myFunction():void{
this.apiService.getData()
.pipe(
  map((response: any) => response.A), // to access to the 'A' array
  take(1)
  )
.subscribe((records: MyType[]) => {
  this.records = records
});
}

This query is the same for each array. Just need to change 'A' by the right array name (B, C).

I don't know if it's possible but what I need is just pass a variable to the function and have a 'switch case' to redirect to the right table.

I watched to switchMap operator but it seems not to be the right solution.

Any suggestion is hepfull

Thanks

CodePudding user response:

If I understand the problem right, it looks you may go with something like this

myFunction(arrayName: string):void{
  this.apiService.getData()
  .pipe(
    map((response: any) => response[arrayName]),
    // you do not need take(1) if the apiService wraps the http client
    // http client notifies one value and then completes immediately after
    )
  .subscribe((records: MyType[]) => {
    this.records = records
  });
}

CodePudding user response:

This solution seems to work but I'm not sure it's the best one.


myFunction(prov: string): void{
    this.jsonService.getData()
      .pipe(
        map((response: any) => 
                prov === "A" ? response.A 
              : prov === "B" ? response.B 
              : prov === "C" ? response.C 
              : ...
              : response.Z
          )
        )
        .subscribe((record: any) =>
        this.records = records
      )
   }

But the solution of Picci is easiest !

  • Related