【问题标题】:Add a "parent" function to run before all components [duplicate]添加“父”功能以在所有组件之前运行[重复]
【发布时间】:2017-10-27 20:26:29
【问题描述】:

我不确定这个术语是什么,但我需要为我的应用程序中的所有组件提供相同的数据。这是我的应用程序的基本结构:

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 中运行一些在我的组件之前编译的东西,并为它们提供所需的数据?

【问题讨论】:

  • 创建一个服务并在需要的地方注入它
  • @OlegMarkoff 那会是什么样子?您介意用示例发布答案吗?

标签: angularjs


【解决方案1】:

在你的 jQuery 函数中,当你解决你的 Promise 时获取数据,将结果分配到一个附加到窗口对象的全局变量中。喜欢:

window.myAppDataModel = new DataModel(response);

在你解决了这个getDataModel函数之后,引导你的角度应用程序。

然后在 angular 内部定义一个常量,将其分配给这个值:

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

然后将此常量注入到您需要它的所有服务/控制器中。

即使这应该可行,我的建议是将此逻辑以角度的形式放入服务内部,并在您的状态的解析块中(或者如果您需要一次,则在引导程序中)执行您的请求并存储值服务内。然后注入服务并访问您需要的数据。

【讨论】:

    猜你喜欢
    • 2020-06-28
    • 2022-06-14
    • 2020-05-18
    • 1970-01-01
    • 1970-01-01
    • 2021-06-26
    • 1970-01-01
    • 2017-07-22
    • 1970-01-01
    相关资源
    最近更新 更多