【问题标题】:How to inject resolved data into controller?如何将解析的数据注入控制器?
【发布时间】:2014-03-02 15:56:29
【问题描述】:

我可以看到在访问此路由之前在 loadProfile 中调用了 RESTful 服务......

$routeProvider.when('/editProfile', {
    templateUrl: '/views/user/editprofile',
    controller: 'UserCtrl',
    access: access.user,
    resolve: {
        userProfile: function(UserSvc){
            UserSvc.loadProfile(function(userProfile){ return userProfile });
        }
    }
});

那么我该如何将这些数据注入到我的用户控制器中?

更新 1

Matt Way 向我介绍了如何将已解析的数据注入到我的控制器中。但是,我立即收到错误“未知提供者:userProfileProvider”。基于其他一些类似的问题,我决定尝试从相关视图中删除 ng-controller="UserCtrl" 属性。我的 /editProfile 路由的 Unknown Provider 错误消失了,但随后开始出现在此控制器的所有其他视图/路由上。

更新 2

我在 egghead.io 上观看了几个视频,发现我能够访问 $route 中承诺的数据。将此添加到我的控制器中,瞧!

if($route.current.locals.userProfile){
    $scope.userProfile = $route.current.locals.userProfile;
}

【问题讨论】:

    标签: angularjs


    【解决方案1】:

    只需将解析项目名称作为控制器函数的输入。例如:

    myApp.controller('UserCtrl', ['$scope', 'userProfile', 
    function($scope, userProfile) {
        // Controller code goes here
    }]);
    

    【讨论】:

    • 有趣。我刚刚尝试过,现在出现错误...“未知提供者:userProfileProvider”
    • 您的routeProvider 配置部分与UserCtrl 是否属于同一模块?
    • 是... angular.module('myApp', ['ngCookies', 'ngRoute', 'ngSanitize']) .config(['$routeProvider', '$locationProvider', '$ httpProvider', function($routeProvider, $locationProvider, $httpProvider) {... var UserCtrl = angular.module('myApp').controller('UserCtrl', ['$rootScope', '$scope', '$sanitize ','$translate','$location','$interval','$timeout','$window','$upload','UserSvc','AuthSvc','MediaSvc',函数($rootScope,$范围, $sanitize, $translate, $location, $interval, $timeout, $window, $upload, UserSvc, AuthSvc, MediaSvc) {
    【解决方案2】:

    您可以返回加载的配置文件吗?我认为这就是您收到未知提供程序错误的原因。

    function (UserSvc) {
        return UserSvc.loadProfile(function(userProfile) { return userProfile });
    }
    

    作为旁注,我在您粘贴控制器功能的地方看到了您的评论,看起来有很多依赖项。减少所需合作者的数量可能会更好。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-03-10
      • 1970-01-01
      • 1970-01-01
      • 2017-08-31
      • 2014-06-12
      • 2017-07-12
      • 1970-01-01
      相关资源
      最近更新 更多