Changes in Observable not reflected in View

后端 未结 3 687
没有蜡笔的小新
没有蜡笔的小新 2021-01-19 19:30

I basically followed this guide to implement an Observable data service.

In a store class (ItemsStore), I have my BehaviorSubject which hol

相关标签:
3条回答
  • 2021-01-19 19:55

    I'm suspicious the problem is in the way you call:

    this.items.next(this.item.getValue().push(newItem));
    

    I don't know what this.item.getValue() returns but if push() method is the same as Array.push() it returns new length (the important thing is it doesn't return this.items with the new item appended).

    The async pipe is defined as:

    The async pipe subscribes to an Observable or Promise and returns the latest value it has emitted.

    So when you call this.items.next(...) the async pipe receives just the new length and tries to iterate it with *ngFor.

    If this.item holds <List<Item>> then you probably want to call:

    this.item.getValue().push(newItem);
    this.items.next(this.item);
    

    Btw, the asObservable() method is used to hide the fact that you're working with Subject. Subject let's you call next() or complete() which is something that you don't want other users to mess with. For this reason it's better to pass everywhere just an Observable and keep Subject only for yourself where you know you need it.

    0 讨论(0)
  • 2021-01-19 20:03

    Solved it - and it was a very stupid mistake - shame on me. ItemsStore gets injected in two different classes, and since the Dependency Injection creates an instance for each injection - well, then we have two of the same kind where there should only be one.

    Moving the dependency (ItemsStore) to the global providers array solved the problem.

    0 讨论(0)
  • 2021-01-19 20:10

    The items property should be Observable, but you set it as BehaviourSubject type. In your link there is:

    @Injectable()
    export class TodoStore {
        private _todos: BehaviorSubject<List<Todo>> = new BehaviorSubject(List([]));
    
        public todos: Observable<List<Todo>> = this._todos.asObservable();
    
        constructor(private todoBackendService: TodoBackendService) {
            this.loadInitialData();
        }
        ...
    }
    

    so assuming you followed this tutorial you should do something like this:

    private _items: BehaviorSubject<List<Item>> = new BehaviorSubject(List([]));
    public items: Observable<List<Item>> = this._items.asObservable();
    
    0 讨论(0)
提交回复
热议问题