Reduce Same http Network call on multiple Component

后端 未结 2 428
醉酒成梦
醉酒成梦 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:10

    Create service like this,

    @Injectable()
    export class DataService {
      public data = null;
    }
    

    add it in providers list in app.module.ts

    and inject it into both components constructor like,

    export class UserComponent {
        constructor(private dataService: DataService)
    }
    

    and when any of the component gets loaded just check if data is null if not make api call and also update data so that later service will not fetch it again.

提交回复
热议问题