Reputation: 2004
Ok can someone please please help me here I feel I'm going crazy!!!
I am having problems getting a list to update in angular2 it seems from looking around I should be using Observables of some sort?
All sounds good but I'm having lots of problems implementing them.
I need help on how to use an observable array and bind to it in angular2 and what are the benefits of using an observable array?
For example I have a list of comments in a model
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 - ??
I have the following div in my template
<div *ngFor="let comment of comments | async | reverseOrder let i = index" >
Ok so far so good but there appears to be NO ability to push or do an onNext with my observable ?!??!!
I have a function called addComment. All I want to do is add a value to my observable array so that my UI updates. I'm not using any data services here..
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??
}
I have done lots of searching and there are suggestions of using Rx Subjects and behaviourSubjects but no examples of how to bind to these in my UI. I get that these are streams but I can't grasp how this would work with my pipes and ordering again no example of this
If I bind directly to my array Angular2 does not detect the changes of the push because it is the same reference.
Other suggestion have been to not use observables at all and just do array.concat to create a new array and a new reference. This seems nuts to me!!!
ObservableArrays seem pointless to me what am I not getting? They certainly don't seem to observe the array, allow me to set a new array value or give me any ability to push onto the array.
Upvotes: 3
Views: 15191
Reputation: 1982
You can try this approach:
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));
}
Upvotes: 9