我的rest Api return { "id": 1, "userId": 1, "date": "2020-03-02T00:00:02.000Z", "products": [ { "productId": 1, "quantity": 4 }, { "productId": 2, "quantity": 1 }, { "productId": 3, "quantity": 6 } ], "__v": 0 } 并且我嘗試實作一個 Angular Material Table其他表選擇的用戶的購物車。我創建了一個材料模塊、服務和介面......有人能幫我理解是什么導致了這里的錯誤嗎?我總是在控制臺中收到此錯誤:提供的資料源與陣列、Observable 或 DataSource 不匹配。
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Cart } from '../interfaces/cart';
import { CartsService } from '../services/carts.service';
@Component({
selector: 'app-user-cart',
templateUrl: './user-cart.component.html',
styleUrls: ['./user-cart.component.css']
})
export class UserCartComponent implements OnInit {
carts!: Cart[];
displayedColumns: string[] = ['id','userId', 'date', 'products-id', 'products-quantity'];
constructor(
private cartsService: CartsService,
private route: ActivatedRoute
) { }
ngOnInit(): void {
this.route.params.subscribe(response => this.cartsService.getCart(response.id)
.subscribe(response => this.carts = response)
);
}
}
<table mat-table [dataSource]="carts" class="mat-elevation-z8">
<ng-container matColumnDef="id">
<th mat-header-cell *matHeaderCellDef> Id </th>
<td mat-cell *matCellDef="let cart"> {{cart.id}} </td>
</ng-container>
<ng-container matColumnDef="userId">
<th mat-header-cell *matHeaderCellDef> User Id </th>
<td mat-cell *matCellDef="let cart"> {{cart.userId}} </td>
</ng-container>
<ng-container matColumnDef="date">
<th mat-header-cell *matHeaderCellDef> Date </th>
<td mat-cell *matCellDef="let cart"> {{cart.date}} </td>
</ng-container>
<ng-container matColumnDef="products-id">
<th mat-header-cell *matHeaderCellDef> Product Id </th>
<td mat-cell *matCellDef="let row">
<span *ngFor="let item of row.products">{{item.productId}}</span>
</td>
</ng-container>
<ng-container matColumnDef="products-quantity">
<th mat-header-cell *matHeaderCellDef> Quantity </th>
<td mat-cell *matCellDef="let row">
<span *ngFor="let item of row.products">{{item.quantity}}</span>
</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;">
</tr>
</table>
export interface Cart {
id: number,
userId: number,
date: string,
products: Array<{productId: number, quantity: number}>,
__v: number
}
uj5u.com熱心網友回復:
不確定這是否可以解決您的問題,但我認為您的資料源不需要串列。
我建議你嘗試更換:
carts!: Cart[];
經過 :
public carts: MatTableDataSource<Cart>;
當然還有相關的匯入: import { MatTableDataSource } from '@angular/material/table';
uj5u.com熱心網友回復:
初始化資料源購物車如下
carts = MatTableDataSource<Cart[]>;
從'@angular/material/table' 匯入 { MatTableDataSource };
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/370249.html
下一篇:在條件下禁用角度材料復選框
