簡體   English   中英

Angular2 http.get啟動和停止

[英]Angular2 http.get start and stop

有了Jquery ajax,我能做到

$(document).ajaxStart(function() { 
                $("body").addClass("loading");    
                }).ajaxStop(function() { 
                    $("body").removeClass("loading"); 
                });

使用Angular2 http.get(),有沒有辦法可以檢測到請求的開始和停止?

謝謝

Angular2 http返回Observables ,這使得一切都非常簡單。

Observable 終於有了方法,你可以把刪除代碼放在里面。

下面的代碼是一個簡單的實現。

document.querySelector('body').classList.add('loading');
this._http.get(url)
  .finally(() => {
    document.querySelector('body').classList.remove('loading');
  })
  .subscribe(
    res => { console.log('success result --', res); },
    err => { console.log('error', err); },
    () => { console.log('completed'); }
  )

如果你想為所有的http get調用實現它。

只需創建如下所示的CustomHttp ,並在您的應用CustomHttp的任何位置使用CustomHttp而不是http

@Injectable()
export class CustomHttp {

  constructor(private _http: Http) {
  }

  get(url: string, options?) {
    document.querySelector('body').classList.add('loading');
    return this._http.get(url, options).finally(() => {
      document.querySelector('body').classList.remove('loading');
    });
  }
}

AngularJS有一個非常有用的功能:HTTP攔截器,這些是在使用$ httpProvider注冊后,在每個ajax請求步驟(ajax調用之前,ajax調用之后等)自動調用的服務。

只需在http.get方法中,您就可以使用以下代碼:

$("body").addClass("loading");
$http.get(url).then(function(value) {
        $scope.example1 = value.status; 
        $("body").removeClass("loading"); 
    });

但是,如果你想要它將全局工作我的意思是每個http(GET / POST)調用它將顯示加載,並在成功/錯誤后隱藏加載。

你可以閱讀這篇文章:

http://www.daveoncode.com/2015/04/29/angularjs-centralized-application-loading-status-handling-using-http-interceptors/

http://codingsmackdown.tv/blog/2013/01/02/using-response-interceptors-to-show-and-hide-a-loading-widget/

我認為它會滿足您的需求。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM