2017-05-26 45 views
0

我不確定術語是什麼,但我需要將相同的數據提供給我的應用中的所有組件。這裏是我的應用程序的基本結構:添加「父」功能在所有組件之前運行

BeforeAngular.js

function DataModel(json){ 
    this.name = json.name || "No name" 
} 

//// JQuery //// 
function getDataModel(name) { 
    return $.get(baseURL + "data-model/" + name).then(response => { 
     return new DataModel(response) 
    }) 
} 

AppSetup.js

var app = angular.module('MyApp', ['ui.router', 'ngResource', ...]); 

app.config(function($stateProvider,$httpProvider,$urlRouterProvider,$sceProvider) { 
    $sceProvider.enabled(false) 

    // Each of these components need `getDataModel()` - how can I do that once and send it to all of them with Angular 
    states = [ 
     { 
      name: 'Interactor', 
      url: '/interactor', 
      component: 'interactorcomponent' 
     }, 
     { 
      name: "otherwise", 
      url: "*path", 
      component: "viewMDLcomponent" 
     } 
    ]; 

    states.forEach(state => $stateProvider.state(state)) 

    $httpProvider.defaults.useXDomain = true; 
    delete $httpProvider.defaults.headers.common['X-Requested-With']; 
} 

ViewMDLComp.js

angular.module("MyApp").component("viewMDLcomponent", { 
    templateUrl: "html/View_MDL.html", 
    controllerAs: "c", 
    controller: [..., View_MDL_Controller] 
}) 

function View_MDL_Controller($http,$timeout,$filter,$log,$q,$sce,l,FileSaver,Blob) { 
    var c = this 

    $q.when(getAllDataModels().then(r => { 
     console.log("getAllDataModels"); 
     c.allMisDataModels = r 
    }) 
} 

那麼,我怎樣才能在我的組件之前編譯Angular中的東西,併爲它們提供他們需要的數據?

+1

創建一個服務並將其注入需要的地方 –

+0

@OlegMarkoff這將是什麼樣子?你介意發佈一個樣本答案嗎? –

回答

0

當你解決你的承諾時,在你的jQuery函數中獲取數據,將結果賦給附加到窗口對象的全局變量。像:

window.myAppDataModel = new DataModel(response); 

然後引導你的角度,你的應用程序解決了這個getDataModel功能後。

然後內部角度定義常量將其分配給該值:

myApp.constant('MY_DATA_MODEL', window.myAppDataModel); 

然後所有的服務/控制器在你需要它裏面注入這個常數。

即使這應該工作,我的建議是將這個邏輯內部角度內部服務,並在您的狀態的決議塊(或只是在引導,如果你需要一次)執行您的請求,並存儲服務內的價值。然後注入服務並訪問您需要的數據。

相關問題