2016-12-13 29 views
0

私は自分のコードベースをcomponent-iseにしようとしており、この問題を抱えています。AngularJS Components - バックエンド変数を渡すにはどうすればよいですか?

$スコープとコントローラを使用する場合、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.options(使用し、その後、2 essesとself.optionss''としてあなたはセーブ機能) ' 1つの属性で 'options'属性を設定すると、決して設定しない属性の' token'にアクセスしようとします。おそらく 'this.restData.options.token'にアクセスして' ss 'を修正すると助けになるでしょうか? – Duncan

+0

これを指摘してくれてありがとう、いくつかのタイプミスがありました。私は今それらを修正しましたが、問題は残っていますが、問題が残ります – EdwardJPayton

+0

'restData: '<'' to 'restData: '@'' – KTU

答えて

1

コントローラがインスタンス化された後にng-initが実行されるという問題があります。ただし、コントローラの構築中にrestDataオブジェクトを作成しているときは、serverTokenは未定義です。ときに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} 
    }; 
    }; 
}) 

:NG-initはこのようなもので呼び出された後、あなたはあなたの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

関連する問題