2016-09-29 89 views
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只是有这一切一些随机文本p元素。

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

编辑:感谢接受的答案下面我有固定我的问题。它与异步调用的问题没有任何关系,但是与我如何定义我的路由和组件有关。请参阅下面的代码修复。再次感谢。

+0

那么我的第一个问题是在我的模板'claimKeys'应该是索赔密钥。然而,这只是解决了一个字符串'$ resolve.claimKeys'...一点点进展,但没有得到任何进一步的。 – Mickers

+0

可能的重复[如何返回来自异步调用的响应?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) –

+0

'return claimKeys'不会将任何内容返回给'$ resolve.claimKeys',因为它是异步的。看到这个笨蛋。 –

回答

8

一些问题:

  • 如你所说claimKeys指令中应该是要求密钥
  • 的结合应该是 '<'(单程绑定)或 '='(双向绑定),但不是'@',它只是传递指令在你的指令控制器中的引号
  • 之间找到的字符串var vm = this;应该在 以上$ onInit功能,而不是在它里面(的范围是不同的)
  • resolve.claimkeys应该返回$ HTTP的承诺,不就叫 它
  • 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,我在这里使用。状态而不是。当进行路由。

+0

感谢您深思熟虑的回复。我从我所关注的一个例子中获得了$决心。我修复它时会使用不同的名称。一旦我有机会实施这些更改,我一定会将其标记为我的答案。 – Mickers