What is the correct way to share the result of an Angular Http network call in RxJs 5?

前端 未结 21 1289
广开言路
广开言路 2020-11-21 06:11

By using Http, we call a method that does a network call and returns an http observable:

getCustomer() {
    return          


        
21条回答
  •  渐次进展
    2020-11-21 06:15

    You could simply use ngx-cacheable! It better suits your scenario.

    The benefit of using this

    • It calls rest API only once, caches the response & returns the same for following requests.
    • Can call API as required after create/ update/ delete operation.

    So, Your service class would be something like this -

    import { Injectable } from '@angular/core';
    import { Cacheable, CacheBuster } from 'ngx-cacheable';
    
    const customerNotifier = new Subject();
    
    @Injectable()
    export class customersService {
    
        // relieves all its caches when any new value is emitted in the stream using notifier
        @Cacheable({
            cacheBusterObserver: customerNotifier,
            async: true
        })
        getCustomer() {
            return this.http.get('/someUrl').map(res => res.json());
        }
    
        // notifies the observer to refresh the data
        @CacheBuster({
            cacheBusterNotifier: customerNotifier
        })
        addCustomer() {
            // some code
        }
    
        // notifies the observer to refresh the data
        @CacheBuster({
            cacheBusterNotifier: customerNotifier
        })
        updateCustomer() {
            // some code
        }
    }
    

    Here's the link for more reference.

提交回复
热议问题