我正在尝试从Angular Material 2应用程序中的服务器获取数据但我在某处做错了可能它没有从服务器加载数据。这不会将我的数据加载到表格中。
userComponent.ts
@Component({
selector: 'app-user',
templateUrl: './user.component.html',
styleUrls: ['./user.component.css']
})
export class UserComponent {
displayedColumns = ['id', 'firstName', 'lastName', 'email'];
dataSource: UserDataSource;
constructor(private userSrvc: UserService) { }
ngOnInit() {
this.dataSource = new UserDataSource(this.userSrvc);
}
logPage(length) {
console.log(length);
}
}
export class UserDataSource extends DataSource<User> {
userSrvc: any;
length = 20;
data: Observable<User[]>;
/** Connect function called by the table to retrieve one stream containing the data to render. */
constructor(userService) {
super();
this.userSrvc = userService;
}
connect(): Observable<User[]> {
this.userSrvc.get().subscribe(users => {
this.data = users;
})
return this.data;
}
disconnect() { }
}
如果我尝试在connect方法内部返回,则会在控制台日志中给出错误。
这是我的 UserService.ts ,我在这里调用用户api来获取数据。
@Injectable()
export class UserService {
constructor(private http: Http) { }
get(): Observable<User[]> {
let header: Headers = new Headers({ 'Content-Type': 'application/json' });
let options: RequestOptions = new RequestOptions({ headers: header });
return this.http.get(`${BASE_URL}user/get/`, options)
.map((response: Response) => {
return <User[]>response.json();
}).catch(this.errorHandler);
}
errorHandler(error: Response) {
return Observable.throw(`Error Message: ${error.statusText}`);
}
}
答案 0 :(得分:0)
我在这里发布了我的代码,用于Firebase的Material数据表。应该主要帮助你的情况。想弄清楚是很棘手的。
Angular Material 2 Data Table Connect to AngularFire2 or Firebase Service?