Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/facebook/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何向每个http请求(angular2)添加预加载程序?_Angular_Angular2 Http - Fatal编程技术网

如何向每个http请求(angular2)添加预加载程序?

如何向每个http请求(angular2)添加预加载程序?,angular,angular2-http,Angular,Angular2 Http,在我的angular2应用程序中,我想在每次http请求启动时显示预加载程序(锁定屏幕),并在请求结束后隐藏它。subscribe方法允许我们检测请求何时成功、何时出错或何时完成。我认为每次我在请求中调用subscribe方法时都编写预加载程序的代码是个坏主意 如何检测请求的开始/结束(subscribe方法除外) 向每个请求添加预加载程序的好方法是什么 你可以通过两种方式做到这一点 创建一个DataService和wrapHttp,将其用于调用API,并将预加载程序逻辑置于服务中 您可以使用拦

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

  • 如何检测请求的开始/结束(subscribe方法除外)
  • 向每个请求添加预加载程序的好方法是什么

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

  • 创建一个DataService和wrap
    Http
    ,将其用于调用API,并将预加载程序逻辑置于服务中

  • 您可以使用
    拦截器
    ,这是一个和


  • 我更喜欢选项1,它更具可扩展性,您可以从一个地方控制所有调用。

    我会像下面那样扩展
    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);
      }
    
      (...)
    }
    
    服务实现可以是这样的:

    export class NotifierService {
      notifier:Subject<any> = new Subject();
    
      notifyBeforeRequest() {
        notifier.next();
      }
    }
    
    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
        });
      }
    
    }