Juan
Juan

Reputation: 2084

Wait for http request in Angular

I'm writing an Angular app. I have a service that makes an http request like this:

export class PingService {

  constructor(
    private http: HttpClient) { }

  ping() {
    return this.http.get<{ip, type}>(this.apiRoutes.pingService);
  }
}

I call this service inside a component:

login(credentials) {
    this.invalidLogin = false;

    this.pingService.ping()
      .subscribe(data => {
        this.apiConfigService.changeNetwork(data.type);
      },
      error => {
        throw(error);
      });

    // MORE THINGS TO DO //

I want to wait for the pingService.ping() to finish before executing the // MORE THINGS TO DO //. How can I wait for the service to finish?

Upvotes: 1

Views: 422

Answers (4)

Guerric P
Guerric P

Reputation: 31835

I'd like to add something regarding other answers.

Most of the time you shouldn't "wait for http requests" in any JavaScript application as it may block the UI. Imagine your user does some action on your app while there's a connection loss or bad network. It would result in the UI being blocked until the request ends or times out, which is really bad experience.

Upvotes: 0

MladenB
MladenB

Reputation: 14

Synchronous is not recommended with Javascript, especially when you are doing http requests. The way guys wrote already is the best way to do it.

Upvotes: 0

user4676340
user4676340

Reputation:

login(credentials) {
    this.invalidLogin = false;

    this.pingService.ping()
      .subscribe(data => {
        this.apiConfigService.changeNetwork(data.type);
        this.doMoreThings();
      },
      error => {
        throw(error);
      });
}

doMoreThings() {
  console.log('I am doing more things');
}

Upvotes: 2

user5283119
user5283119

Reputation:

login(credentials) {
this.invalidLogin = false;

this.pingService.ping()
  .subscribe(data => {
    this.apiConfigService.changeNetwork(data.type);

    --> To here // MORE THINGS TO DO //
  },
  error => {
    throw(error);
  });

--> Move this    // MORE THINGS TO DO //

Upvotes: 1

Related Questions