angularjs – Angular ui-router获取异步数据的解决方案

前端之家收集整理的这篇文章主要介绍了angularjs – Angular ui-router获取异步数据的解决方案前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想显示一个带有对应于编辑项目的数据的表单。我使用ui路由器路由。我定义了一个状态:
myapp.config(function($stateProvider) {

    $stateProvider.
    .state('layout.propertyedit',{
        url: "/properties/:propertyId",views : {
            "contentView@": {
                templateUrl : 'partials/content2.html',controller: 'PropertyController'
            }
        }
    });

在PropertyController中,我想设置$ scope.property与来自以下调用(Google Cloud Endpoints)的数据:

gapi.client.realestate.get(propertyId).execute(function(resp) {
        console.log(resp);
    });

我不知道如果我可以使用解决,因为数据是异步返回。我试过了

resolve: {
        propertyData: function() {
            return gapi.client.realestate.get(propertyId).execute(function(resp) {
                console.log(resp);
            });
        }
    }

第一个问题,propertyId是未定义的。如何从url:“/ properties /:propertyId”获取propertyId?

基本上,我想在PropertyController中将$ scope.property设置为由异步调用返回的resp对象。

编辑:

myapp.controller('PropertyController',function($scope,$stateParams,$q) {

    $scope.property = {};

    $scope.create = function(property) {
    }

    $scope.update = function(property) {
    }

function loadData() {
    var deferred = $q.defer();

    gapi.client.realestate.get({'id': '11'}).execute(function(resp) {
        deferred.resolve(resp);
    });

    $scope.property = deferred.promise;
}

});
你需要读取 the docs for resolve. Resolve函数是可注入的,你可以使用$ stateParams从你的路由获取正确的值,像这样:
resolve: {
    propertyData: function($stateParams,$q) {
        // The gapi.client.realestate object should really be wrapped in an
        // injectable service for testability...

        var deferred = $q.defer();

        gapi.client.realestate.get($stateParams.propertyId).execute(function(r) {
            deferred.resolve(r);
        });
        return deferred.promise;
    }
}

最后,解析函数的值可注入到控制器中:

myapp.controller('PropertyController',propertyData) {

    $scope.property = propertyData;

});
原文链接:https://www.f2er.com/angularjs/145419.html

猜你在找的Angularjs相关文章