添加一个“父级”函数在所有组件运行之前运行。
添加一个“父级”函数在所有组件运行之前运行。
这个问题已经有了答案:
我不确定这个术语是什么,但我需要将相同的数据提供给我应用程序中的所有组件。这是我的应用程序的基本结构:
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中运行一些在我的组件之前编译并提供它们需要的数据?
admin 更改状态以发布 2023年5月22日
在你的jQuery函数中获取数据时,当你解决promise时,把结果赋值给一个附加到window对象的全局变量。例如:\n
window.myAppDataModel = new DataModel(response);
\n解决这个`getDataModel`函数后,在Bootstrap你的Angular应用程序。\n然后在Angular中定义一个常量将其分配给这个值:\n
myApp.constant('MY_DATA_MODEL', window.myAppDataModel);
\n然后在所有需要它的服务/控制器中注入此常量。\n即使这种方法可以工作,我的建议是将这个逻辑放在Angular的一个服务中,在你的状态的resolve块中(或者只是在Bootstrap时如果你需要一次性的)执行请求,并将该值存储在服务中。然后注入该服务并在需要时访问数据。