我正在使用6.3的NGX数据表,它无法绑定到可观察的集合。如何将Angular Observable Collection转换为常规的不可观察数组?
以下是我的服务内容:
private _productUrl = '../../api/todos/todos.json';
constructor(private _http: Http) { }
getToDos(): Observable<IToDo[]> {
return this._http.get(this._productUrl)
.map((response: Response) => <IToDo[]> response.json())
.do(data => console.log('All: ' + JSON.stringify(data)))
.catch(this.handleError);
}
以下是我对component.ts的看法。它在foreach循环中给出了一个错误:无法读取未定义的属性“长度”
ngOnInit() {
this._toDoService.getToDos()
.subscribe(
toDos => this.toDos = toDos,
error => this.errorMessage = <any>error);
this.rows = this.transform(this.toDos);
}
transform(source: IToDo[]): IToDo[] {
let dest: IToDo[] = [];
for (let sourceItem of source)
{
let destItem: IToDo = {
toDoId: sourceItem.toDoId,
name: sourceItem.name,
priority: sourceItem.priority,
dueDate: sourceItem.dueDate,
completed: sourceItem.completed
};
dest.push(destItem);
}
return dest;
}
答案 0 :(得分:2)
Observables是异步的,所以你不能在你做的订阅电话之后立即操作待办事项。相反,操纵订阅内的待办事项:
ngOnInit() {
this._toDoService.getToDos()
.subscribe(
toDos => {
this.toDos = toDos
this.rows = this.transform(this.toDos);
},
error => this.errorMessage = <any>error);
}
你的this.transform调用是同步调用的,这意味着你的调用堆栈只是一个线性的调用进程。
答案 1 :(得分:0)
您也可以使用async管道解包输入Observable。
<ngx-datatable
class="material"
[rows]="todos | async"
......
</ngx-datatable>