angular 1.6 $http.get(...).success is not a function 解決辦法

一、現狀

使用了angular1.6最新版,運行以前的項目報錯,按F12打開調試界面,控制檯輸出以下信息$http.get(...).success is not a function,也就是說找不到success方法,同樣也找不到error方法。

二、原因

通過google一通,發現angular從1.5版本起就多了一個then方法,並不再建議使用success和error方法(but沒有移除)。但是從1.6版本開始,angular正式移除了success和error方法,這也是我們使用angular最新版跑以前的項目時候會報以上錯誤的原因。

三、解決辦法

1、方案一:使用新的then方法替代

基本語法如下:

// Simple GET request example:
$http({
  method: 'GET',
  url: '/someUrl'}).then(function successCallback(response) {
    // this callback will be called asynchronously
    // when the response is available
  }, function errorCallback(response) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
  });

2、方案二:使用angular 1.5版本(同時兼容兩種寫法)

如果是舊的項目,建議採用這種方案,否則以前的代碼大量使用了.success()和.error()改起來會非常的蛋疼!!

四、參考

關於angular $http使用的官方文檔:
https://docs.angularjs.org/api/ng/service/$http

Tips:網上有些文章比較過時,大家可以優先考慮看下官方文檔,示例也很齊。

發佈了48 篇原創文章 · 獲贊 660 · 訪問量 81萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章