Angular Material - 使用服务获取 mat-table 一列的值

问题描述

情况

我有一个表,里面填满了接口 A 的数据。但是其中一列应该填入基于接口 A 的 id 过滤后的接口 B 数据。

我的尝试

html:

<mat-table [dataSource]="dataSource">
    ...
    <ng-container matColumnDef="title">
        <mat-header-cell *matHeaderCellDef> Title</mat-header-cell>
        <mat-cell *matCellDef="let element"> {{getValueOfInterfaceB(element.id)}} </mat-cell>
    </ng-container>
    ...
</mat-table>

ts:

getValueOfInterfaceB(id: number){
    let filter: any = {Id: id}
    this.entrieService.getEntries(filter).subscribe((entries: Entry[]) => {
        console.log(entries);
    })
}

问题

如果我运行应用程序,这些行将一遍又一遍地执行。如果我不想一遍又一遍地运行代码,我该如何解决这个问题?


编辑:尝试@EliSEO解决方案时出错

error TS2304: Cannot find name 'res'.
res[] => {

error TS1011: An element access expression should take an argument.
res[] => {

error TS1005: ',' expected.
res[] => {

error TS18004: No value exists in scope for the shorthand property 'res'. Either declare one or provide an initializer.
res.forEach((value,index)=>{

error TS2769: No overload matches this call.
res.forEach((value,index)=>{

解决方法

向对象数组添加新属性比在 .html 中调用函数更好。如果“计算列”来自 API,您应该创建一个订阅数组(使用 map)并使用 forkJoin 订阅 obs 数组

我想你有一组数据 [{Id:0},{Id:1}....]

你做了类似的事情

//create an array of obs
const obs$[]=this.dataarray.map(x=>this.entrieService.getEntries({Id:x.id})
//subscribe to forkJoin
forkJoin(obs).subscribe(res[]=>{
    //in res[0] you has the response to this.entrieService.getEntries({Id:0})
    //in res[1] you has the response to this.entrieService.getEntries({Id:1})
    ...
    //so you can iterate using forEach and index and make some like
    res.forEach((value,index)=>{
        this.dataarray[index].newProperty=value
    })
}

然后创建数据源。记住,如果你有一个复杂的“列计算”,在 ngOnInit 中只计算一次列

,

你可以这样做:

'

此外,您可以在 html 中添加异步管道

/run/some/setup -o1 option1 -option2 '$SOME_ENV_2_EXEC -option3 hi'
/run/some/setup -o1 option1 -option2 "hi"
/run/some/setup -o1 $SOME_ENV_2_EXEC