簡體   English   中英

在angularjs中調用http(RESTFUL WebAPI)的正確方法

[英]proper way to call http (RESTFUL WebAPI) in angularjs

我有以下控制器代碼

module.registerController('DemoCtrl', function ($scope, myFactory) {
        myFactory.get(function (data) {
            console.log(data); /// data is always undefined 
        });
    });

並跟隨工廠調用restful webapi

module.registerFactory('myFactory', ['$http',
    function ($http) {
            function get(callback) {
                $http.get('mywebapiurl')
                    .success(function (response) {
                        //debugger; data comes back from server
                        callback(response);
                    }).error(function (response, status, headers, config) {
                        callback(response);
                    });
            }

        return {
            get: get
        }
    }]);

工廠正在調用webapi服務,並確實獲取了數據。 但是在控制器中,數據不會返回。

我在這里錯過明顯的東西嗎? 也不確定這是否是使用factory在controller中的angularjs中調用webservice的最佳方法。 任何輸入都是最歡迎的。

謝謝,

控制器代碼

module.registerController('DemoCtrl', function ($scope, myFactory) {
    myFactory.get("url").then(function(d) {
            console.log(d.data); 
        }
    });
});

調用寧靜的webapi的工廠

module.registerFactory('myFactory', ['$http',
function ($http) {
         var apiFactory = {
               get:function(url){
                   return $http.get(url);
               }
         }
    return apiFactory;
}]);

工廠的成敗

module.registerFactory('myFactory', ['$http',
function ($http) {
     var apiFactory = {
           get:function(url){
               return $http.get(url).then(function(response){
                      // success
                      return responce.data;
               },function(error){
                      //failure
                      return error;
               };
           }
     }
    return apiFactory;
}]);

您想返回一個promise,而不是傳遞一個回調。 由於$http.get已經返回了一個承諾,您可以直接返回該承諾,或者派生的承諾直接返回響應數據。 順便說一句,您的factory看起來應該是一種service而不是:

angular.moudule('yourApp')
.service('myService', ['$http', myService]);

function myService($http) {
    this.get = function(url) {
        return $http.get(url)
                   .then(function transformData(response){
                       return response.data;
                   }).catch(function onError(rejectionResponse){
                       //Whatever you want to do here
                   });
    }
}

這樣myService.get將返回你可以一個承諾.then() .catch().finally()你想要什么,住在編碼風格的框架。 例如:

var squirrels = [];
myService.get('http://squirrelshop.com/api/squirrels')
    .then(function(squirrelsData){
        console.log('Got the squirrels!');

        squirrels = squirrelsData;
    }).catch(function(rejection){
        console.warn('Couldnt fetch squirrels. Reason: ' + rejection);
    });

暫無
暫無

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

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