Reduce Same http Network call on multiple Component

后端 未结 2 406
醉酒成梦
醉酒成梦 2021-01-28 11:38

I have 2 components UsersComponent and HelloComponent.

I am calling the same service with the same api calls on both the component.

But I want is that if UsersCo

2条回答
  •  离开以前
    2021-01-28 12:13

    This is called as cold observables. Whenever you subscribe to it, it'll make a new HTTP request.

    Because every time you return a new http.get call.

    The solution here is to return the same pointer to that observable every time.

    @Injectable()
    export class AppService {
    
      private data$: Observable;
    
      constructor(private http: HttpClient) {}
    
      getData() {
         if (!this.data$) {
            this.data$ = this.http.get('https://jsonplaceholder.typicode.com/posts');    
         }
         return this.data$;
      }
    }
    

    However, you can use rxjs share operator as well.

提交回复
热议问题