如何在$ http.get返回后调用函数

时间:2017-10-19 16:24:04

标签: javascript angular ngrx-store

我已经实施了ngrx-store。我试图在http调用之前打开微调器。并在通话结束后将其关闭。

   getInspectionDetails(order) {
    this.store.dispatch({ type: SPINNER_VISIBLE, payload: true }) //<-- spinner on
    return this.$http.get(this.url+'api/Inspection/'+order.documentNumber)
        .map(this.httpHelper.extractData)
        .catch(this.httpHelper.handleError)
        .map(payload => ({ type: INSPECT_PURCHASE_ORDER, payload }))
        .subscribe(action => this.store.dispatch(action))});
}

现在我正在尝试使用

this.store.dispatch({ type: SPINNER_VISIBLE, payload: false }) 

关闭微调器。基本上它是与假负载相同的调用来关闭微调器。 但我应该把它放在哪里?

1 个答案:

答案 0 :(得分:1)

subscribe方法有3个参数:

httpRequest.subscribe(
    action => // do something when the value arrives
    error => // do something when error occurres
    () => // do something when observable completes
);

或者你可以在observable上使用finally方法:

getInspectionDetails(order) {
  this.store.dispatch({ type: SPINNER_VISIBLE, payload: true }) //<-- spinner on
  return this.$http.get(this.url+'api/Inspection/'+order.documentNumber)
      .map(this.httpHelper.extractData)
      .catch(this.httpHelper.handleError)
      .finally(() => this.store.dispatch({ type: SPINNER_VISIBLE, payload: false }))
      .map(payload => ({ type: INSPECT_PURCHASE_ORDER, payload }))
      .subscribe(action => this.store.dispatch(action));
}

第二种方法可能更好,因为发生错误时不会触发完整的回调。更多关于这个问题的区别:

https://github.com/angular/angular/issues/7865