加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 08:31:46 所属栏目:安全 来源:网络整理
导读:我想显示一个带有对应于编辑项目的数据的表单。我使用ui路由器路由。我定义了一个状态: myapp.config(function($stateProvider) { $stateProvider. .state('layout.propertyedit',{ url: "/properties/:propertyId",views : { "contentView@": { templateUr
我想显示一个带有对应于编辑项目的数据的表单。我使用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;

});

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读