2017-06-22 25 views
0

我有這樣的構造函數:的方式來抽象的角度UI路由器狀態解析成一個構造函數

function State(url, templateUrl, controller, controllerAs, factory, resolveProp){ 
    this.url = url 
    this.templateUrl = templateUrl 
    this.controller = controller 
    this.controllerAs = controllerAs 
} 

,並在我的路由器的回調我有這樣的:

$stateProvider 
    .state('archetypes', new State('/admin/archetypes', './resources/features/admin/archetypes/index.html', 'archetypes', 'aaVM')) 

這工作得很好。然而,我有另一條路線,其中包含獲得一些後端數據的決心。

我想我也許能爲我的構造做這樣的事情:在這種方式

function State(url, templateUrl, controller, controllerAs, factory, resolveProp){ 
    this.url = url 
    this.templateUrl = templateUrl 
    this.controller = controller 
    this.controllerAs = controllerAs 
    if(factory){ 
    this.resolve = {} 
    this.resolve[resolveProp] = function(factory){ 
     return factory.getAll() 
    } 
    } 
} 

然後實例的狀態:

.state(
    'archetypes', 
    new State(
     '/admin/archetypes', 
     './resources/features/admin/archetypes/index.html', 
     'archetypes', 
     'aaVM', 
     ArchetypesFactory, 
     'archetypes' 
    ) 
) 

但我認爲.state方法調用控制器來處理解析對象,這樣當我嘗試上述狀態實例時,它會出錯,因爲ArchetypesFactory顯然是未定義的。

需要注意的是,當我寫這樣我的狀態:

.state('archetypes', { 
    url: '/admin/archetypes', 
    templateUrl: './resources/features/admin/archetypes/index.html', 
    controller: 'archetypes', 
    controllerAs: 'aaVM', 
    resolve: { 
    archetypes: function(ArchetypesFactory){ 
     return archetypesFactory.getAll() 
    } 
    } 
}) 

它工作正常。

有沒有什麼辦法可以將狀態配置對象解析爲構造函數或ES6類?

回答

1

解析器函數由AngularJS注入器調用。注射器需要明確的註釋形式。一種方法是使用Inline Array Annotation

function State(url, templateUrl, controller, controllerAs, factory, resolveProp){ 
    this.url = url; 
    this.templateUrl = templateUrl; 
    this.controller = controller; 
    this.controllerAs = controllerAs; 
    if(factory){ 
    this.resolve = {} 
    this.resolve[resolveProp] = [factory, function(factory){ 
     return factory.getAll(); 
    }]; 
    }; 
} 

然後指定一個字符串爲工廠參數:

.state(
    'archetypes', 
    new State(
     '/admin/archetypes', 
     './resources/features/admin/archetypes/index.html', 
     'archetypes', 
     'aaVM', 
     //ArchetypesFactory, 
     //USE string 
     'ArchetypesFactory', 
     'archetypes' 
    ) 
) 

串聯陣列註釋是註釋的應用程序組件的首選方式。使用這種類型的註釋時,注意保持註釋數組與參數在函數聲明中同步。

+0

太棒了,這完美的作品。 –

相關問題