Angular 6 http request handling

sesmajster

I'm building a web app using Angular 6. I have a service that has a method which when called and given right parameters, sends a POST request to the server and returns the data. This is the method:

  public getDataFromServer(request, url): any {
      return this.httpClient.post(url, request, {headers: new HttpHeaders().set(this.headername, this.header ) });
  }

Now I have multiple components which uses this method. Every page in the menu (home, about, news, etc..) uses this. I want to make a request handler that would send the first request (let's say I login) and then wait until I get a response before sending another request. If I were to click on page news and then on page about before I would get response, I would already be on page about and after I get response the next request will be the one on page news, but I'm already on page about. I don't want request on news to be executed if I'm on page about.

I saw some posts with http interceptor, but I don't want the request to even be made to http. Request must not be sent. Thank you for your help in advance.

Carsten

I think the reason that people don't respond to your question is because it's somewhat of a story. Simplifying your questions like: "I don't want to receive a callback when i have left the page" would increase answers in my opinion.

That being said.

The thing you're looking for is called unsubscribe. httpClient.post returns an Observable on which you probably .subscribe() subscribe returns a subscription which you can use to unsubscribe. For example:

@Component({etc.etc})
export class MyComponent implements OnInit, OnDestroy {

  subscription;

  constructor(private service: Service) {} // Whatever your service is called

  ngOnInit() {
    this.subscription = this.service.getDataFromServer().subscribe(
      response => {
        console.log(response);
        this.subscription = undefined;
      },
      error => {
        console.log(error);
        this.subscription = undefined;
      }
    );
  }

  ngOnDestroy() {
    if (this.subscription) {
      this.subscription.unsubscribe();
    }
  }
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related