2

在我的 angular2 应用程序中,我想在每次http请求开始时显示一个预加载器(锁定屏幕)并在请求结束后隐藏它。subscribe 方法允许我们检测请求何时成功、出现错误或完成。我认为每次在请求上调用 subscribe 方法时编写预加载器的代码是个坏主意。

  1. 如何检测请求开始/结束(订阅方法除外)?
  2. 将预加载器添加到每个请求的好方法是什么?
4

2 回答 2

2

我会Http像下面这样扩展类并添加一个包含可观察/主题的服务,以便在执行 HTTP 请求时得到通知

export class CustomHttp extends Http {
  constructor(backend: ConnectionBackend,
        defaultOptions: RequestOptions,
        private _notifierService:NotifierService) {
    super(backend, defaultOptions);
  }

  request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
    this._notifierService.notifyBeforeRequest();
    return super.request(url, options);
  }

  get(url: string, options?: RequestOptionsArgs): Observable<Response> {
    this._notifierService.notifyBeforeRequest();
    return super.get(url, options);
  }

  (...)
}

如下所述注册它:

bootstrap(AppComponent, [HTTP_PROVIDERS,
    {
      provide: Http,
      useFactory: (backend: XHRBackend, defaultOptions: RequestOptions, notifyService:NotifierService) => {
        return new CustomHttp(backend, defaultOptions, notifyService);
      },
      deps: [XHRBackend, RequestOptions, NotifierService]
    }
]);

服务实现可能是这样的:

export class NotifierService {
  notifier:Subject<any> = new Subject();

  notifyBeforeRequest() {
    notifier.next();
  }
}

您可以通过以下方式收到通知:

@Component({
  (...)
})
export class SomeComponent {
  constructor(private notifyService:NotifierService) {
    this.notifyService.notifier.subscribe(() => {
      // do something
    });
  }

}
于 2016-07-11T12:11:25.583 回答
1

你可以通过两种方式做到这一点

  1. 创建一个 DataService 并包装Http它将用于调用 API,将您的预加载器逻辑投入服务。

  2. 你可以使用,这里和这里Interceptor是一个例子

我更喜欢可扩展性更强的选项 1,您可以从一个地方控制所有呼叫。

于 2016-07-11T11:07:29.217 回答