我正在尝试使用Angular 4 Material MatTable从我的服务器更新它, 问题是它只能工作一次。
我有一个激活搜索功能的搜索按钮,它工作一次并更新表格,但在第二次搜索时,似乎只是更改列表长度而不更新任何行数据。
我的猜测是我只是没有正确使用BehaviorSubject或者我应该告诉angular以某种方式刷新数据因为它似乎表改变了它的长度(列表的滚动条变短)但它只是不刷新数据
import { Component, OnInit } from '@angular/core';
import { DataSource } from '@angular/cdk/collections';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { DialogService } from "ng2-bootstrap-modal";
import { ServerApiService } from "../../services/ServerApi.service";
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/startWith';
import 'rxjs/add/observable/merge';
import 'rxjs/add/operator/map';
import 'rxjs/add/observable/of';
import {Product} from "../../Models/Product";
import {Offer} from "../../Models/Offer";
import {OffersComponent} from "../Offers/Offers.component";
@Component({
selector: 'app-store-stats',
templateUrl: './search-product.component.html',
styleUrls: ['./search-product.component.less'],
providers: [DialogService]
})
/** StoreStats component*/
export class SearchProductComponent implements OnInit {
keyword: string;
displayedColumns = ['image', 'position', 'name', 'weight','offers'];
dataSubject = new BehaviorSubject<Product[]>([]);
dataSource = new ExampleDataSource(this.dataSubject);
canSearch = true;
constructor(private serverApi: ServerApiService, private dialogService: DialogService) {
}
showOffers(Offers: Offer[]) {
this.dialogService.addDialog(OffersComponent, {
title:'Offers',
modalOffers: Offers});
}
trackByFn(index: number) {
return index;
}
Search() {
this.canSearch = false;
this.serverApi.getProducts(this.keyword)
.subscribe(
(response) => {
let data:Product[] = response.json() as Product[];
this.dataSubject.next(data);
this.canSearch = true;
},
(error) => {
this.canSearch = true;
console.log(error);
}
);
}
/** Called by Angular after StoreStats component initialized */
ngOnInit(): void { }
}
/**
* Data source to provide what data should be rendered in the table. The observable provided
* in connect should emit exactly the data that should be rendered by the table. If the data is
* altered, the observable should emit that new set of data on the stream. In our case here,
* we return a stream that contains only one set of data that doesn't change.
*/
var Offers: Offer[] = new Array<Offer>();
Offers[0] = new Offer("123123", 2,"NEW");
Offers[1] = new Offer("123123", 2,"Like New");
export class ExampleDataSource extends DataSource<Product> {
constructor(private subject: BehaviorSubject<Product[]>) {
super ();
}
/** Connect function called by the table to retrieve one stream containing the data to render. */
connect(): Observable<Product[]> {
return this.subject;
}
disconnect() { }
}
答案 0 :(得分:1)
我似乎没有正确使用表格的TrackBy功能, 导致它无法理解项目何时发生变化。