2016-09-29 99 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