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

いくつかの問題:

  • あなたが言ったように、ディレクティブのクレームキーはクレームキーでなければなりません
  • そのバインディングは「<」(一方向バインディング)または「=」(双方向バインディング)である必要がありますが、引用符で囲まれた文字列をディレクティブに渡すだけの「@」ではありません
  • ディレクティブのコントローラー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 に答える