Angular rxjs 条件获取查询
Angular rxjs conditional get query
我的 json 文件包含几个数组,如下所示:
{
A[]
B[]
C[]
...
}
我的查询如下所示:
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
});
}
这个查询对于每个数组都是一样的。只需要将 'A' 改成正确的数组名 (B, C).
我不知道这是否可能,但我需要的只是将一个变量传递给函数并有一个 'switch case' 重定向到右边 table.
我查看了 switchMap 运算符,但它似乎不是正确的解决方案。
任何建议都是hepfull
谢谢
如果我对问题的理解是正确的,看来你可以采用这样的方式
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
});
}
这个解决方案似乎可行,但我不确定它是不是最好的解决方案。
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
)
}
但 Picci 的解决方案是最简单的!
我的 json 文件包含几个数组,如下所示:
{
A[]
B[]
C[]
...
}
我的查询如下所示:
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
});
}
这个查询对于每个数组都是一样的。只需要将 'A' 改成正确的数组名 (B, C).
我不知道这是否可能,但我需要的只是将一个变量传递给函数并有一个 'switch case' 重定向到右边 table.
我查看了 switchMap 运算符,但它似乎不是正确的解决方案。
任何建议都是hepfull
谢谢
如果我对问题的理解是正确的,看来你可以采用这样的方式
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
});
}
这个解决方案似乎可行,但我不确定它是不是最好的解决方案。
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
)
}
但 Picci 的解决方案是最简单的!