Search code examples
angularrxjsobservablebehaviorsubject

How to use BehaviourSubject to get All Items and Single Item?


I am using the BehaviorSubject following the article here:

https://coryrylan.com/blog/angular-observable-data-services

In this article the author is using loadAll() to load all items and load() for a single entry. load() will then push the retrieved item into the dataStore which then gets sent into the next(...) function, so that all subscribers get notified. I am not sure 100% sure if this is the right approach. I am not sure why, but it just seems strange to me that this is how we should design our services. I could be wrong, since I am new to BehaviorSubject. So my question is, is this the correct way to retrieve all items and a single item or is there a better way?


Solution

  • From what I am seeing ... way too many devs are using BehaviorSubject when a simpler solution would suffice.

    BehaviorSubject is really only needed if you have complex requirements to watch for data changes when the data is not bound. Otherwise, simple data binding handles watching for changes for you.

    This is the code I have in my service for getting all and getting one:

    getProducts(): Observable<IProduct[]> {
        return this._http.get<IProduct[]>(this._productUrl)
            .do(data => console.log('All: ' + JSON.stringify(data)))
            .catch(this.handleError);
    }
    
    getProduct(id: number): Observable<IProduct> {
        return this.getProducts()
            .map((products: IProduct[]) => products.find(p => p.productId === id));
    }
    

    I modified the plunker from the link provided by the OP and my results are here: https://plnkr.co/edit/r5PMFprgoWbzmFPTK3xN?p=preview

    Note that it provides the same basic functionality with NO BehaviorSubject and much more simplified code.