完整错误消息:
“ 类型'Observable'不能分配给类型'DataListeItem []'。 类型“可观察”中缺少属性“包含”。”
我正在使用材料表示意图,现在我想从Rest服务中填充列表。 data-liste-datasource.ts
import { DataSource } from '@angular/cdk/collections';
import { MatPaginator, MatSort } from '@angular/material';
import { map } from 'rxjs/operators';
import { Observable, of as observableOf, merge } from 'rxjs';
import { AuthService } from '../auth.service';
export interface DataListeItem {
name: string;
id: number;
email: string;
number: number;
}
export class DataListeDataSource extends DataSource<DataListeItem> {
data: DataListeItem[] = this.authservice.GetUser(); <-- error here!
constructor(private paginator: MatPaginator, private sort: MatSort, private authservice: AuthService) {
super();
}
connect(): Observable<DataListeItem[]> {
const dataMutations = [
observableOf(this.data),
this.paginator.page,
this.sort.sortChange
];
this.paginator.length = this.data.length;
return merge(...dataMutations).pipe(map(() => {
return this.getPagedData(this.getSortedData([...this.data]));
}));
}
disconnect() { }
private getPagedData(data: DataListeItem[]) {
const startIndex = this.paginator.pageIndex * this.paginator.pageSize;
return data.splice(startIndex, this.paginator.pageSize);
}
private getSortedData(data: DataListeItem[]) {
if (!this.sort.active || this.sort.direction === '') {
return data;
}
return data.sort((a, b) => {
const isAsc = this.sort.direction === 'asc';
switch (this.sort.active) {
case 'name': return compare(a.name, b.name, isAsc);
case 'email': return compare(a.email, b.email, isAsc);
case 'id': return compare(+a.id, +b.id, isAsc);
case 'number': return compare(+a.number, +b.number, isAsc);
default: return 0;
}
});
}
}
function compare(a, b, isAsc) {
return (a < b ? -1 : 1) * (isAsc ? 1 : -1);
}
auth.service.ts
import { Injectable } from '@angular/core';
import { HttpHeaders, HttpClient } from '../../node_modules/@angular/common/http';
import { Observable } from '../../node_modules/rxjs';
import { DataListeItem } from './data-liste/data-liste-datasource';
@Injectable({
providedIn: 'root'
})
export class AuthService {
constructor(private http: HttpClient) { }
GetUser(): Observable<DataListeItem[]> {
return this.http.get<DataListeItem[]>("DataListeItem.online");
}
因此,所有有关如何调用REST并显示列表的方法。 我应该直接在“ data-liste-datasource.ts”中进行呼叫还是应该在服务中。
感谢阅读
答案 0 :(得分:1)
您需要使用Observable<DataListeItem[]>
代替DataListeItem []。
data: Observable<DataListeItem[]> = this.authservice.GetUser();