【问题标题】:Undefined resolve property in controller控制器中未定义的解析属性
【发布时间】:2017-11-04 03:55:16
【问题描述】:

我在我的路由 .state 中解析了我返回的列表(来自服务器的数据),该列表是在我在 .state 路由中 console.log 时定义的,但在控制器中当我 console.log 时它是未定义的。我正在使用 ionic 1 和 AngularJS。

路线

.state('app', {
  url: '/app',
  abstract: true,
  templateUrl: 'templates/menu.html',
  controller: 'AppCtrl',
  controllerAs: 'appcn',
  resolve: {
    notificationsResolve: function ($http) {
      $http.defaults.headers.common.Authorization = "Basic MzEwMzIzOjEyMw==";
      return $http.get("http://192.168.178.24:8090/notifications/")
              .then(function (response) {
                return response.data;
              });
    }
  }
})

控制器

angular.module('starter.controllers', ['appServiceAPI'])

.controller('AppCtrl', ['notificationService', function($ionicModal, $timeout, notificationsResolve,
                                                        notificationService) {

  var vm = this;

  console.log("resolve: " + notificationsResolve);

  vm.notifications = notificationsResolve;

【问题讨论】:

    标签: angularjs controller angular-ui-router undefined resolve


    【解决方案1】:

    参数和它们的名字必须匹配

    // this is wrong
    .controller('AppCtrl', 
      ['notificationService', 
      function($ionicModal, $timeout, notificationsResolve, notificationService)
    
    // this correct
    .controller('AppCtrl', 
      ['$ionicModal', '$timeout', 'notificationsResolve', 'notificationService',
      function($ionicModal, $timeout, notificationsResolve, notificationService)
    

    【讨论】:

      【解决方案2】:
      .controller('AppCtrl', ['notificationService', 
                      function($ionicModal, $timeout, notificationsResolve, notificationService) {
      

      您忘记了数组中的 4 个参数中的 3 个。应该是

      .controller('AppCtrl', ['$ionicModal', '$timeout', 'notificationsResolve', 'notificationService', 
                      function($ionicModal,   $timeout,   notificationsResolve,   notificationService) {
      

      或者更好的是,您应该只使用基本语法,没有这种丑陋且容易出错的重复,并使用ng-annotate 使您的代码可以为您缩小。

      【讨论】:

      • 正是这个......这就是问题所在,最好使用插件来完成这项任务,而不是把它搞砸 1000 次并且每次都感到困惑。
      猜你喜欢
      • 1970-01-01
      • 2016-02-18
      • 2015-09-20
      • 1970-01-01
      • 2021-08-14
      • 2014-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多