angular使用原廠模式封裝公用的 ajax 非同步互動

來源:互聯網
上載者:User

標籤:method   obj   .ajax   工廠   bsp   項目   cat   control   jquery   

在開發過程中,我們會不可避免的用到 ajax 互動,每一個都需要寫 $http,然而寫多了會發現,這個維護性不高,而且重複的代碼太多,不適合進行快速開發。

  比如這樣:

  $http({

     url:"test.php",

     method:"POST",

     data:JSON.stringify({name:"tao"}),

     headers:{"Content-Type":"application/json"}

  }).then(function(data){

  }),function(err){

  }

當你的項目夠大的時候,你會發現,經常這樣寫會很煩惱,有很多重複的代碼。導致項目維護困難,那麼用原廠模式是怎麼解決的呢?

看代碼

app.factory("http",function($http,$q){//注入http服務,$q 的promise;

var obj={};

obj.ajax=function(method,url,data){

  var promise=$q.defer();//取到promise,promise是個比較進階的api,jQuery和各大架構都有,ES5沒有這個概念,在ES6當中已經存在了

  $http({

     url:url,

     method:method,

     data:JSON.stringify(data),

     headers:{"Content-Type":"application/json"}

  }).then(function(data){

  promise.resolve(data)

  }),function(err){

  promise.reject(err)

  }

return promise.promise;

}

return obj;

})

這個工廠服務的代碼就完成了。

只要在controller中注入這個服務"http"就可以使用了,

調用代碼

.controller(‘myctrl‘,[‘$scope‘,‘http‘,function($scope,http){

  http.ajax(‘get‘,‘test.php‘).then(function(data){

  //data就是擷取到的資料了

})

}])

寫的不好,請見諒。

angular使用原廠模式封裝公用的 ajax 非同步互動

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.