如何异步获取mat表每一行的数据 [英] how to get data for each row of the mat table asynchronously
问题描述
我正在使用 mat-table ,
I am using a mat-table ,
表的每一行有八列,给表的数据源只填充了表的每一行的4列,对于每行剩下的4列我们要请求另一个api,在它的api中,每行的id也必须发送
each row of the table has eight columns , the data source given to the table fills only 4 columns in each row of the table , for the remaining 4 columns of each row we have to request another api , In its api, the id of each row must also be sent
有人可以指导我吗?
推荐答案
您需要创建一个包含所有列的数据.所以你应该使用 rxjs 操作符:switchMap、forkJoin 和 map
you need create a data with all the columns. So You should use rxjs operators: switchMap, forkJoin and map
想象一下你有一个有两个功能的服务
Imagine you has a service that has two functions
list() //return an observable of array of items
read(id) //return an element given an "id"
您可以在您的服务中创建一个返回列表的函数,但与读取"的所有属性互补
you can create a function in your service that return the list, but complementary with all the properties of the "read"
readFull()
{
return this.list().pipe(switchMap((res:any[])=>{
return forkJoin(res.map((x:any)=>this.read(x.id).pipe(
map((more:any)=>({...x,...more})
))))
}))
}
有点复杂,我试着解释一下.首先想象你有一个对象
It's a bit complex, I try to explain. First imagine you has an object
x={id:1,name:"one"}
//when you make
this.read(x.id).pipe(
map((more:any)=>{
return {...x,...more}
})
)
你得到一个具有x"所有属性的对象;以及从 this.read() 接收的所有属性
You get an object with all the properties of "x" and all the properties that received from this.read()
好吧,假设您没有单个对象,而是一个对象数组.您可以将对象数组转换为 observables 数组
Well, imagine you don't has a single object else an array of object. you can transform the array of object in an array of observables
res=[{id:1,name:"one"},{id:2,name:"two"}]
res.map((x:any)=>the before function
当我们有一组 observables 时,我们可以使用 forkJoin 将它们连接在一起
When we has an array of observables we can join all in one using forkJoin
forkJoin(..the array of observables..)
好吧,首先我们得到了list",但是我们对list"没有兴趣否则 observable 由 forkjoin 创建.为此,我们需要使用 switchMap
Well, first we get the "list", but we are not interesting in the "list" else the observable create by the forkjoin. For this we need use switchMap
您可以在 this 中看到这个概念stackblitz 当我模拟"时使用of"读取并列出
You can see the concept in this stackblitz when I "simulate" read and list using "of"
这篇关于如何异步获取mat表每一行的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!