我的角度应用程序中有一个数据源,由HTTP服务/调用填充。我能够从远程服务器获取数据,使用该数据实时构建表并进行编辑。我现在想要能够在本地删除数据表中的一行,而不是将更改推回到服务器。但我无法看到我能够访问数据数组的位置。我知道它必须存储在某个地方的数组中,但在哪里?数以万计的不同控制台日志使我无法确定数据的实际位置,因此我可以对其进行操作。我的观察者工作得很好,可以给我显示的数据。这是数据源的代码:
import { Aircraft } from '../shared/aircraft';
import { AircraftInfoService } from './aircraft-info.service';
import { BehaviorSubject } from 'rxjs';
import { CollectionViewer, DataSource } from '@angular/cdk/collections';
import { Observable } from 'rxjs';
import { of } from 'rxjs';
import { catchError, finalize } from 'rxjs/operators';
export class AircraftInfoDataSource implements DataSource<Aircraft> {
private className: string;
private aircraftDBSubject = new BehaviorSubject<any[]>([]);
private loadingSubject = new BehaviorSubject<boolean>(false);
public loading$ = this.loadingSubject.asObservable();
constructor(private aircraftInfoService: AircraftInfoService) {
this.className = this.constructor.toString().match(/\w+/g)[1];
}
connect(collectionViewer: CollectionViewer): Observable<Aircraft[]> {
return this.aircraftDBSubject.asObservable();
}
disconnect(collectionViewer: CollectionViewer): void {
this.aircraftDBSubject.complete();
this.loadingSubject.complete();
}
getAllAircraftData() {
this.loadingSubject.next(true);
this.aircraftInfoService.getAllAircraftRecords().pipe(
catchError(() => of([])),
finalize(() => this.loadingSubject.next(false))
)
.subscribe((data:any[]) => this.aircraftDBSubject.next(data));
}
deleteAircraft( deviceID: string ) {
console.log(this.className, ' going to delte aircraft: ', deviceID);
console.log('aircraftDBSubject: ', this.aircraftDBSubject);
const foundIndex = this.aircraftDBSubject.value.findIndex(x => x.id === this.deviceID);
console.log('foundIndex=',foundIndex);
}
}
deleteAircraft函数是我遇到问题的地方。这里也是检索数据的数据服务:
import { Aircraft } from '../shared/aircraft';
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class AircraftInfoService {
aircraft: Aircraft[];
getApi = 'https://<removed>';
constructor(private httpClient: HttpClient) {
}
ngOnInit() {
console.log('aircraftInfoservice');
}
getAllAircraftRecords() {
return this.httpClient.get(this.getApi)
}
}
所以一切都是只读的,我怎么修复它所以我也可以写(即删除记录)?
谢谢....
嘿伙计...
这是我的建议。尝试从服务级别拆分值。因此,在您的组件中,处理任何事件都很容易。
找到下面的示例。
服务代码
getAllAircraftRecords(): Observable<any> {
return this.httpService.post(this.getApi)
.pipe(map(res => res),
map((res: Response) => res),
catchError((error: Response) => Observable.throw(error)));
}
零件
getAllAircraftData() {
this.loadingSubject.next(true);
this.aircraftInfoService.getAllAircraftRecords().subscribe(
data => {
this.aircraftDB=data;
this.loadingSubject.next(false);
},
err => {
this.loadingSubject.next(false);
});
}
deleteAircraft( deviceID: string ) {
this.aircraftDB = this.aircraftDB.filter(x=>x.deviceID!=deviceID);
}
this.aircraftDB你可以用它来绑定。
希望这可以帮助...