代码之家  ›  专栏  ›  技术社区  ›  Juan

以角度等待http请求

  •  0
  • Juan  · 技术社区  · 8 年前

    我在写一个角度应用程序。我有一个服务发出如下http请求:

    export class PingService {
    
      constructor(
        private http: HttpClient) { }
    
      ping() {
        return this.http.get<{ip, type}>(this.apiRoutes.pingService);
      }
    }
    

    我在组件内部调用此服务:

    login(credentials) {
        this.invalidLogin = false;
    
        this.pingService.ping()
          .subscribe(data => {
            this.apiConfigService.changeNetwork(data.type);
          },
          error => {
            throw(error);
          });
    
        // MORE THINGS TO DO //
    

    我想等 pingService.ping() 在执行 // MORE THINGS TO DO // . 我怎样才能等服务结束呢?

    4 回复  |  直到 8 年前
        1
  •  2
  •   Maryannah    8 年前
    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');
    }
    
        2
  •  1
  •   swonder    8 年前
    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 //
    
        3
  •  0
  •   MladenB    8 年前

    不建议使用javascript进行同步,尤其是在执行http请求时。男人的写作方式是最好的方式。

        4
  •  0
  •   Guerric P    8 年前

    我想补充一些关于其他答案的内容。

    大多数情况下,您不应该在任何javascript应用程序中“等待http请求”,因为它可能会阻塞ui。假设您的用户在连接断开或网络故障时对您的应用程序执行某些操作。这将导致用户界面被阻塞,直到请求结束或超时,这是非常糟糕的体验。