Reduce Same http Network call on multiple Componen

2020-05-01 09:37发布

问题:

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 UsersComponent is calling the api than HelloComponent should not call the api it should recieve the value from UsersComponent.

Currently network call is happening on both of the component.

Is there any way to do.Please help.

Stackblitz link:

Stackblitz

回答1:

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.



回答2:

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<any>;

  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.



标签: angular http