简体   繁体   中英

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?

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');
}
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 //

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.

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.

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