在控制器的Angular 4中,我可以在$ http请求之前以及成功/错误之后插入“事件”来执行吗?

问题描述 投票:0回答:2

我有一个SPA,需要处理大量数据。通常,即使我正在调用的API不能很快返回结果,我也需要一个响应式UI。这意味着我需要经常将SPA置于“ Loading ...”状态。

我可以通过设置一个加载标志来做到这一点,当状态改变时,Angular UI会关闭它,但是看起来像这样:


$scope.requestFooData = function() {

   var parameters = $scope.BuildFooParams();

   //'loadingData' is a state variable that the UI uses 
   //for disabling regions, or showing spinners where 
   //and when applicable.
   $scope.loadingData = true;
   $http.get("API/getFoo" + parameters)
       .success(function(data) {
           //Handle data
           $scope.loadingData = false;
       })
       .error(function() {
           //Address the error
           $scope.loadingData = false;
       });
}

可以,但是至少要记住三行代码才能集成到每个请求中。不仅如此,我还需要在对成功事件的后续调用中掩埋一些API调用,因为结果可能会级联更多的API调用。在这种情况下,最好插入可以确定何时正确设置加载状态的信号量。在这种方法下,逻辑变得更加复杂和复杂。

有一种方法可以在初始化控制器时注入“事件”方法,该方法会在发出任何Web请求(GET / POST /等)时触发,一旦结果返回,它就会为“清理”?

我希望有一个解决方案。有没有更好的方法来更新应用程序的“正在加载数据”状态?

javascript angular angular-http
2个回答
0
投票

主题是掌握rxjs库功能的强大方法。在这种情况下,ReplaySubject管理组件的加载状态。要更改组件的加载状态,请在主题中使用布尔值:

import { ReplaySubject } from 'rxjs';
import { HttpClient } from '@angular/common/http';

export class Component {
  loading = false;

  $loading = new ReplaySubject(1);

  constructor(protected httpClient: HttpClient) {}

  makeRequest(endpoint) {
    this.$loading.next(true);

    this.httpClient.get(endpoint).subscribe(response => {
      // handle response

      this.$loading.next(false);
    });
  }

}


0
投票

您应该使用HttpInterceptor。例如,使用繁忙的布尔属性制作一些AppStateService,将一些标记绑定到它,然后创建httpintercepter,它将将该属性设置为请求状态。

© www.soinside.com 2019 - 2024. All rights reserved.