Angular ui-router get asynchronous data with resolve

前端 未结 4 802
忘了有多久
忘了有多久 2020-12-12 20:51

I want to display a form with data corresponding to the edited item. I use ui-router for routing. I defined a state:

myapp.config(function($stat         


        
4条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-12 21:32

    Try this easy way to use resolve in proper way

    State code:


    .state('yourstate', {
                    url: '/demo/action/:id',
                    templateUrl: './view/demo.html',
                    resolve:{
                        actionData: function(actionData, $q, $stateParams, $http){
                           return actionData.actionDataJson($stateParams.id);
                        }
                    },
                    controller: "DemoController",
                    controllerAs : "DemoCtrl"
                })
    

    In the above code I am sending parameter data which I am sending in the url,For examples if i send like this /demo/action/5 this number 5 will go to actionData service that service retrieve some json data based on id.Finally that data will store into actionData You can use that in your controller directly by using that name

    Following code return some JSON data based on id which iam passing at state level


    (function retriveDemoJsonData(){
    
        angular.module('yourModuleName').factory('actionData', function ($q, $http) {
    
            var data={};
            data.actionDataJson = function(id){
               //The original business logic will apply based on URL Param ID 
                var defObj = $q.defer();
                $http.get('demodata.json')
                    .then(function(res){
                         defObj.resolve(res.data[0]);
                    });
                return defObj.promise;  
            }
            return data;
        });
    
    })();
    

提交回复
热议问题