pco2699’s blog

学んだものについて、メモしておく場所

AngularJSのcomponentにui.routerのresolveの変数を注入を試してみる→失敗しました...

AngularJSのcomponentにui.routerのresolveの変数を注入する方法がわからなく
色々調べたのメモしておく。

結論から言うとui.routerは0.2系のverだとcomponentで注入するのは無理そう。。。
(こうやれば解決できる!的な解決策あれば教えてほしいです)

当初書いたコードはこんな感じ
まずステート定義から

angular.module('myApp', [ui.router])
   .state('main', {
     url: 'main',
     resolve: {
        test: function ($http) {
          return $http.get({
            url: '/api/test/'
          });
        }
     },
     template: '<main></main>'
   })

コンポーネント部はTypeScriptで記述

class mainComponent{
    constructor(public test){
    }
    // 機能記述...
}

angular.module('myApp')
   .component('main', {
     templateUrl: 'main.html',
     controller: mainComponent
   }
);

ここでmainComponentでそんなサービスないよボケと怒られるわけである。
(testがサービスとみなされ、AngularJSで怒られる。)

なんとかならんかと色々ググってみたところ以下のサイトを発見

www.codelord.net

The beloved ui-router doesn’t really support exposing resolved dependencies except to the controller of the state.
The maintainers mentioned this might be addressed in the upcoming 1.0 version of ui-router.

オゥ、ui-routerはresolveの依存性注入はコントローラー以外できないってバッチリ書いてありまっせ。。。
ui.router 1.0では解決されまっせ、とのことです。

というわけで素直に、resolveで解決するのを諦めて$onInitで取りに行く形としました。

angular.module('myApp', [ui.router])
   .state('main', {
     url: 'main',
     template: '<main></main>'
   })
class mainComponent{
    constructor(){
    }
    $onInit{
       $http.get('/api/test')
       .then(
         //機能記述...
       )
    }
}

angular.module('myApp')
   .component('main', {
     templateUrl: 'main.html',
     controller: mainComponent
   }
);