2016-12-13 21 views
0

我想組件是我的代碼庫,並且遇到了這個問題。AngularJS組件 - 如何傳入後端變量?

當使用$ scopes和Controllers時,我會使用ng-init將服務器令牌傳遞給我的rest調用方法。嘗試對組件執行相同操作不起作用。

的JavaScript

angular 
.module('myApp', []) 

.controller('mainCtrl', function() { 
    var self = this; 

    self.options = function() { 
    var o = {} 
    o.token = self.serverToken 
    return o; 
    } 

    self.restData = { 
    url: 'http://rest.url', 
    options: self.options() 
    } 
}) 

.component('myComponent', { 
    bindings: { 
    restData: '<' 
    }, 
    template: '<p>template, calls child components</p>', 
    controller: function(restService) { 

    this.callRestService = function() { 
     restService.get(this.restData.url, this.restData.options) 
    } 

    console.log(this.restData.url) // http://rest.url 
    console.log(this.restData.options) // {token: undefined} 
    } 
}) 

HTML

<html ng-app="myApp"> 
    <!-- head --> 

    <body ng-controller="mainCtrl as m" ng-init="m.serverToken='12345'"> 
    <my-component rest-data="m.restData"></my-component> 
    </body> 

</html> 

如何傳遞價值的組成部分?

+0

您保存功能'self.optionss'有兩個esses,然後你用'self.options()'用一個ess來設置一個屬性'options',然後你嘗試訪問一個你從未設置過的屬性'token'。也許訪問'this.restData.options.token'並更正'ss'會有幫助嗎? – Duncan

+0

嘿,謝謝你指出,有幾個拼寫錯誤。我已經糾正了他們,但問題仍然存在 – EdwardJPayton

+0

嘗試'restData:'<''到'restData:'@'' – KTU

回答

1

問題是在實例化控制器後執行ng-init。但是,在構建控制器期間,您正在創建restData對象,此時serverToken未定義。

NG-init的調用後像這樣的東西你可以建立你的restData對象:然後

.controller('mainCtrl', function() { 
    var self = this; 
    self.restData = {}; 

    self.init = function(token) { 
    self.serverToken=token; 
    self.restData = { 
     url: 'http://rest.url', 
     options: {token:token} 
    }; 
    }; 
}) 

你的組件可以做一些事情時restData變化。例如:

.component('myComponent', { 
    bindings: { 
    restData: '<' 
    }, 
    template: '<p>template, calls child components</p>', 
    controller: function(restService) { 

    this.callRestService = function() { 
     restService.get(this.restData.url, this.restData.options) 
    } 

    this.$onChanges = function(changes) { 

     console.log(this.restData) // http://rest.url 
     console.log(this.restData.options) // {token: 12345} 

     this.callRestService(); 
    } 
    } 
}); 

的HTML會改變調用你的init方法:

<body ng-controller="mainCtrl as m" ng-init="m.init(12345)"> 
    <my-component rest-data="m.restData"></my-component> 
    </body> 
+0

我試過類似的東西 - 在一個函數中設置令牌 - 但無法讓它工作。這是$ onChanges在這裏起作用嗎?這解決了它對我來說,非常好的解決方案。 – EdwardJPayton

相關問題