繁体   English   中英

Angular 材料表数据源不接受来自 app.service.ts 的 Observable

[英]Angular Material Table dataSource won't accept Observable from the app.service.ts

我正在 Angular 中构建一个简单的网上商店应用程序,我想在 Angular 材料表中展示我通过该服务获得的产品。 我有一个产品界面:

export interface Product {
    id: number;
    name: String;
    price: number;
}

我的资产文件夹中有一个 products.json。 在我的服务 class 中,有 getProducts() 方法可以返回到 json(将来可能返回到更远的后端):

private products_url = "/assets/data/products.json";

  public getProducts(): Observable<Product[]> {
    //return this.http.get<Product[]>(`${this.apiServerUrl}/product/all`);
    return this.http.get<Product[]>(this.products_url);
  }

在我的组件 class 中,我有一个 getProducts() function 可以访问该服务:

  public getProducts(): void {
    this.canteenService.getProducts().subscribe(
      (response: Product[]) => {
        this.products = response;
      },
      (error: HttpErrorResponse) => {
        alert(error.message);
      }
    )
  }

当我想以一种通过组件中的 getProducts() function 获取产品的方式声明材料表的数据源时,出现错误。

  public dataToDisplay = this.getProducts();;
  public dataSource = new ExampleDataSource(this.dataToDisplay);

错误提示:“void”类型的参数不可分配给“Product[]”类型的参数.ts(2345)

我怎样才能解决这个问题?

你需要知道 Observable 是如何工作的。 Observable 是异步的。 所以你不会在订阅 function 中得到其他响应。所以你需要

dataSource:MatDataSource<any> //outside you declare the variable

public getProducts(): void {
    this.canteenService.getProducts().subscribe(
      (response: Product[]) => {
        this.products = response;
        //here asign the matDataSource
        this.dataSource = new MatDataSource(this.dataToDisplay);
      },
      (error: HttpErrorResponse) => {
        alert(error.message);
      }
    )
  }

顺便说一句,如果你不需要排序或分页,垫表的数据源可以是一个数组,所以你可以使用异步 pipe

dataSource$=this.canteenService.getProducts() //<--see that is an observable

<table mat-table [dataSource]="dataSource$ |async">
   ...
</table>

注意:由于缺陷,您声明的组件的所有变量都是公共的,因此没有必要使用public variable:any -您可以声明为variable:any -

您组件中的 function getProducts()不返回任何内容,您甚至将返回类型设置为void ,此外,此特定 function 的命名约定是错误的,因为您没有get任何东西

我建议您执行以下操作:

getProducts$(): Observable<Product[]> {
  return this.canteenService.getProducts();
}
<table [dataSource]="getProducts$()">
 <...>
</table>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM