简体   繁体   English

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

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

I am building a simple webshop app in Angular and I want to represent products I get thru the service in an Angular Material Table.我正在 Angular 中构建一个简单的网上商店应用程序,我想在 Angular 材料表中展示我通过该服务获得的产品。 I have a Product interface:我有一个产品界面:

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

I have a products.json in my assets folder.我的资产文件夹中有一个 products.json。 In my service class have getProducts() method that reaches back to the json (in the future possibly to a more distant backend):在我的服务 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);
  }

In my component class I have a getProducts() function that reaches out to the service:在我的组件 class 中,我有一个 getProducts() function 可以访问该服务:

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

When I want to declare the dataSource for the Material Table in a way that it gets the products thru this getProducts() function in the component, I get an error.当我想以一种通过组件中的 getProducts() function 获取产品的方式声明材料表的数据源时,出现错误。

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

The error says: Argument of type 'void' is not assignable to parameter of type 'Product[]'.ts(2345)错误提示:“void”类型的参数不可分配给“Product[]”类型的参数.ts(2345)

How can I fix this?我怎样才能解决这个问题?

You need know how work an Observable.你需要知道 Observable 是如何工作的。 An Observable is asyncronous. Observable 是异步的。 So you don't get the response else inside subscribe function. So you need所以你不会在订阅 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);
      }
    )
  }

BTW, if you don't need sort or paginate, the data source of a mat-table can be an array, so you can use async pipe顺便说一句,如果你不需要排序或分页,垫表的数据源可以是一个数组,所以你可以使用异步 pipe

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

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

NOTE: By defect all the variables of a component you declare are public, so it's unnecessary use public variable:any -you can declare as variable:any -注意:由于缺陷,您声明的组件的所有变量都是公共的,因此没有必要使用public variable:any -您可以声明为variable:any -

Your function getProducts() from your component doesn't return anything, you even set the return type as void , also, the naming convention for this particular function is wrong since you are not get ting anything您组件中的 function getProducts()不返回任何内容,您甚至将返回类型设置为void ,此外,此特定 function 的命名约定是错误的,因为您没有get任何东西

I suggest you do the following:我建议您执行以下操作:

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

暂无
暂无

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

相关问题 Angular 单元测试:如何使用 Jasmine-Karma 为 app.service.ts 编写单元测试用例 - Angular Unit Testing: How to write unit testcases for the app.service.ts using Jasmine-Karma Angular Material Table 不会显示 Observable&lt;{ [key: string]: number; }&gt; - Angular Material Table won't display Observable<{ [key: string]: number; }> 当数据源为 Observable 时,如何在 Angular Material Data Table 中启用排序<T> - How to enable sorting in Angular Material Data Table, when the datasource is Observable<T> 合并两个 Observable 并作为 Angular 材料表的单个 Observable 传入 dataSource - Merge two Observables and pass into dataSource as a single Observable for Angular material table 运行 Angular Universal 应用程序失败 - 不会从单独的项目编译 app.module.ts 或识别服务 - Running Angular Universal app fails - won't compile app.module.ts from separate project or recognize service Angular 6材质表数据源 - Angular 6 Material table datasource Angular 12 材料表。 [dataSource] 错误:提供的数据源与数组、Observable 或 DataSource 不匹配 - Angular 12 Material table. [dataSource] error: Provided data source did not match an array, Observable, or DataSource Paginator没有正确使用表数据源使用角度材料为角度2应用程序 - Paginator not properly working with table Datasource using angular material for angular 2 app 以对象为数据源的角度材料表 - Angular Material Table with object as datasource 使用 angular 数据源使用来自 API 的数据填充材料表 - Fill material table with data from API using angular DataSource
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM