Angular/RxJS 6: How to prevent duplicate HTTP requests?

前端 未结 6 1541
自闭症患者
自闭症患者 2020-12-29 21:35

Currently have a scenario where a method within a shared service is used by multiple components. This method makes an HTTP call to an endpoint that will always have the same

6条回答
  •  旧巷少年郎
    2020-12-29 22:06

    Late to the party, but I created a reusable decorator specifically to address this use-case. How does it compare to the other solutions posted here?

    • It abstracts all the boilerplate logic out leaving your app's code clean
    • It handles methods with arguments and assures not to share calls to the method with different args.
    • It provides a way to configure when exactly you want to share the underlying observable (see docs).

    It's published under an umbrella I'll be using for various Angular-related utilities.

    Install it:

    npm install @ngspot/rxjs --save-dev
    

    Use it:

    import { Share } from '@ngspot/rxjs/decorators';
    
    class SharedService {
      constructor(private http: HttpClient) {}
    
      @Share()
      getSomeData(): Observable {
        return this.http.get('some/endpoint');
      }
    }
    

提交回复
热议问题