6

我正在尝试将我的第一个角度组件与 ngRoute 放在一起,但到目前为止我无法获取数据来解析。配置:

.when('/myfirstcomponent', {
    template: '<myfirstcomponent claimKeys="$resolve.claimKeys"></myfirstcomponent>',
    resolve: {
        claimKeys: ['$http', function($http) {
            $http.get('server/claimkeys.json').then((response) => {
                var claimKeys = response.data.DATASET.TABLE;
                return claimKeys;
            });
        }]
    }
})

零件:

    .component('myfirstcomponent', {
        bindings: {
            'claimKeys': '@'
        },
        templateUrl: 'components/component.html',
        controller: [function() {
            this.$onInit = function() {
                var vm = this;
                console.log(vm.claimKeys);
            };


        }]

该组件的 html 仅包含带有一些随机文本的 ap 元素。

我可以在调试时看到我正在检索数据,但我无法在组件控制器上访问它......

编辑:感谢下面接受的答案,我已经解决了我的问题。它与异步调用的问题无关,而是与我定义路由和组件的方式有关。请参阅下面的代码进行修复。再次感谢。

4

1 回答 1

9

一些问题:

  • 正如你所说,指令中的claimKeys应该是claim-keys
  • 它的绑定应该是'<'(单向绑定)或'='(双向绑定),而不是'@',它只是传递给指令在引号之间找到的字符串
  • 在你的指令的控制器中var vm = this;应该在 $onInit函数之上而不是在它里面(范围不同)
  • resolve.claimkeys应该返回 $http 的 promise 而不仅仅是调用它
  • claimKeys应该被路由器的控制器作为注入接收并传递给它的模板
  • controllerAs: '$resolve'应该被路由器使用

    app.component('myfirstcomponent', {
      bindings: {
        'claimKeys': '='
      },
      template: 'components/component.html',
      controller: function() {
        var vm = this;
        this.$onInit = function() {            
          console.log(vm.claimKeys);
        };
      }
    });
    
    app.config(function ($stateProvider) {
      $stateProvider.state('myfirstcomponent', {
        url: '/myfirstcomponent',
        template: '<myfirstcomponent claim-keys="$resolve.claimKeys"></myfirstcomponent>',
        resolve: {
          claimKeys: ['$http', function($http) {
            return $http.get('claimkeys.json').then((response) => {
              return response.data.DATASET.TABLE;
            });
          }]
        },
        controller: function (claimKeys) {
          this.claimKeys = claimKeys;
        },
        controllerAs: '$resolve'
      })
    });
    

plunker:http ://plnkr.co/edit/Nam4D9zGpHvdWaTCYHSL?p=preview ,我在这里使用.state而不是.when进行路由。

于 2016-09-29T21:06:22.207 回答