好的,有人可以请帮助我,我觉得我快疯了!!!
我在获取要在 angular2 中更新的列表时遇到问题,环顾四周,我似乎应该使用某种 Observables?
一切听起来都不错,但我在实施它们时遇到了很多问题。
我需要关于如何使用可观察数组并在 angular2 中绑定到它的帮助,以及使用可观察数组有什么好处?
例如,我有一个模型中的评论列表
this.comments = new Array<IComment>;
this.observableComments = Observable.from(this.comments);
// Note what is really odd with the above is typescript thinks
// the above is Observable<IComment> ??? not Observable<IComment[]>
// but when i debug it is ObservableArray with array property - ??
Run Code Online (Sandbox Code Playgroud)
我的模板中有以下 div
this.comments = new Array<IComment>;
this.observableComments = Observable.from(this.comments);
// Note what is really odd with the above is typescript thinks
// the above is Observable<IComment> ??? not Observable<IComment[]>
// but when i debug it is ObservableArray with array property - ??
Run Code Online (Sandbox Code Playgroud)
到目前为止一切顺利,但似乎没有能力用我的 observable 推送或执行 onNext ?!??!!
我有一个名为 addComment 的函数。我想要做的就是向我的可观察数组添加一个值,以便我的 UI 更新。我没有在这里使用任何数据服务..
addComment(comment: IComment) {
this.comments.push(comment);
this.observableComments.onNext(this.comments);
// The above does not work
// neither onNext - next - push is a function on my observable array??
}
Run Code Online (Sandbox Code Playgroud)
我已经做了很多搜索,并且有使用 Rx Subjects 和 behaviorSubjects 的建议,但没有关于如何在我的 UI 中绑定到这些的示例。我知道这些是流,但我无法理解这将如何与我的管道一起使用并再次订购没有这样的例子
如果我直接绑定到我的数组 Angular2 不会检测推送的变化,因为它是相同的引用。
其他建议是根本不使用 observables,只需执行 array.concat 来创建一个新数组和一个新引用。这对我来说似乎很疯狂!!!
ObservableArrays 对我来说似乎毫无意义我没有得到什么?他们当然似乎没有观察数组,允许我设置一个新的数组值或给我任何推送到数组的能力。
你可以试试这个方法:
private comments: IComment[];
private observableComments: BehaviorSubject<IComment[]>;
constructor() {
this.comments = new Array<IComment>;
this.observableComments = <BehaviorSubject<IComment[]>>new BehaviorSubject([]);
}
get comments() {
return this.observableComments.asObservable();
}
addComment(comment: IComment) {
this.comments.push(comment);
this.observableComments.next(Object.assign({}, this.comments));
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13321 次 |
| 最近记录: |