简体   繁体   中英

How to subscribe to an ongoing http request

I need to request some data from the server only once, then use it as long as the app is loaded

getData(callback: Function) {
 if (this.data) {
  callback(this.data);
 } else {
  this.query.http.get('url', res => {
   this.data = res;
   callback(this.data);
  });
 }
}

the problem is that when the app starts a lot of components request the data at once, resulting in 30-40 http request, so I came up with this solution:

getData(callback: Function) {
 if (this.data) {
  callback(this.data);
 } else if(!this.gettingData) {
  this.gettingData = true;
  this.query.http.get('url', res => {
   this.data = res;
   callback(this.data);
  });
 } else {
  setTimeout(() => {
   getData(callback);
  }, 500)
 }
}

so it requests the data again after 500ms if the http request is in progress, if the request returns an error I reset the gettingdata to false, it works, but it feels dirty and wrong, how can I subscribe to the ongoing http request called by another function invoker?

how about this?

getData () {
    this.query.http.get('url'). subscribe(
    res=> this.data = res,
    err=> console.log(err));
}

then just use this.data throughout your component, you could emit the data if it's from a child component like so

@Output() valueChange = new EventEmitter();

private data;

getData () {
    this.query.http.get('url'). subscribe(
    res=> {
          this.data = res;
          this.valueChange.emit(this.data);
    },
    err=> console.log(err));
}

i hope this helps. or somewhat answers your question

introduce a service which manages your http requests. A service is basically a singleton which can be used via dependency injection. Create it with

ng -generate service myservice

and inject it by declaring a field of type myservice as a constructor argument of your component.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM