簡體   English   中英

如何使用angularjs中的http get從工廠返回業務對象

[英]How to a return business object from factory using http get in angularjs

我是AngularJs的新手。 任何人都可以幫助在angularJS中使用http服務編寫工廠,以便工廠成功后向我返回業務對象,而不是promise或將值分配給scope變量。 我在網絡上研究了很多文章,但是所有文章都使用了回調函數或通過從http服務返回promise。
要求:假設XMLtoJsonService是我的工廠,它將本地文件夾中的xml轉換為json。 工廠應該是退貨業務對象,以便在我的控制器中,我可以按照以下方式使用

    //controller 
    var obj = XMLtoJsonService.MethodName(); 

**(No promises or callback function should be used in controller)** 
/*******service code****************/

    App.factory('XmlToJsonSvc',
            [ '$http', function($http) {
                return {
                    get : function(path, callback) {
                        $http.get(path, {
                            transformResponse : function(data) {
                                // convert the data to JSON and provide
                                // it to the success function below
                                var x2js = new X2JS();
                                var json = x2js.xml_str2json(data);
                                return json;
                            }
                        }).success(function(data, status) {
                            //console.log('Sucess');

                            callback(data);
                        })
                    }
                }
    } ]);

/*********Controller Code **********/
var setData = function(data) {

            return new Menus(data);

            debugger
        }
        var path = "Configs/Config.xml";
        XmlToJsonSvc.get(path, setData);

//此代碼可以正常工作//但我的要求是轉換此代碼,以便在控制器中//類似於var obj = XmlToJsonSvc.get(path)// obj應該具有json對象,而我將使用其他服務

 <!--In this funcion calling factory function restCall() from controller. before that i have assigned a already created factory object to a scope variable in controller .So whenever factory varaible updates,that update will be available to controller automatically. Some kind of 2-way binding method from factory object--> <!DOCTYPE html> <html lang="en" ng-app="app"> <head> <meta charset="UTF-8"> <title>Test</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> </head> <body ng-controller="myCtrl"> {{obj.data1}} <button ng-click="clickFn()">Clicking this will call service</button> <script> (function() { var app = angular.module("app",[]) .controller("myCtrl",function(myFactory,$scope){ $scope.obj = myFactory.bObject; $scope.clickFn = function(){ myFactory.restCall(); } }).factory("myFactory",function($timeout){ var bObject = { data1 :null }; function restCall(){ $timeout(function(){ bObject.data1 = bObject.data1 ? false : true ; },1000); } var service = { bObject : bObject, restCall : restCall, } return service; }); }()); </script> </body> </html> 

暫無
暫無

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

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