如何在Typescript中从响应的特定属性分配表数据源



我有一个简单的typescript方法来获取列表和状态,我的模型是:

export interface CashPaymentModel  {
success: boolean;
data: CashSpendAdHocDTO[];
}
export interface CashSpendAdHocDTO  {
dueDate: string;
gross: string;
moveStageName: string;
paidDate: string;
service: string;
status: string;
timestamp: string;
type: string;
}

我的服务方式是:

getCashPayments(policyVersionId: number, employeeId: number): Observable<CashPaymentModel> {
return this.http.get<CashPaymentModel>(`/api/v1/policy/configuration/versions/${policyVersionId}/details?employeeId=${employeeId}`);
}

在模板中,我想在表中显示响应中的列表(响应中的第二个属性(,但我如何分配该表的数据源?

tableDataSource: Observable<CashPaymentModel>;
testMethod() {
this.tableDataSource = this.cashPaymentService.getCashPayments(this.policyVersionId, this.employeeId).subscribe((data: CashPaymentModel) => {
this.tableDataSource = data; .......BLA BLA BLA
});
}

在ts中,如何从响应的第二个属性正确分配tableDataSource?

根据您的接口结构,您可以尝试:

testMethod() {
this.tableDataSource = this.cashPaymentService.getCashPayments(this.policyVersionId, this.employeeId).subscribe((data: CashPaymentModel) => {
this.tableDataSource = data.data;
});
}

您应该首先筛选未定义的响应,并在success-的情况下将tableDataSource分配给responsedata属性(根据您的接口(。

试试这个:

tableDataSource: Observable<CashPaymentModel>;
testMethod() {
this.tableDataSource = this.cashPaymentService.getCashPayments(this.policyVersionId, this.employeeId).pipe(
filter(res => res !== undefined),
).subscribe((res: CashPaymentModel) => {
if (res.success) {
this.tableDataSource = res.data;
} else {
// handle false success
// usually you should not send 200 response code for false success and handle it in 
// err block of subscribe
}
});
}

最新更新