typescript - 在加载 AngularJS 应用之前从 AJAX 获取数据
我们正在准备升级我们的 AngularJS 应用程序并为此进行重构。目前我们遇到了一个架构问题:
我们的应用程序目前通过 jQuery AJAX 调用加载 JSON,这会设置所有数据,然后引导应用程序。
然而,我们需要将 AJAX 调用移到 Angular 中,以便我们可以在不等待 AJAX 返回的情况下引导应用程序(这是升级所必需的)
$.get('/ajax/init').done(function (initData) {
walletApp.run([
'SomeService', function (someService) {
// ...
},
]);
walletApp.config([
'SomeProvider', function (someProvider) {
// ...
},
]);
walletApp
.factory('navInfo', function () {
return initData.navInfo;
})
.factory('userInfo', function () {
return initData.userInfo;
});
// ETC
// Below is the important line
angular.bootstrap(document, ['walletApp']);
});
我一直在尝试类似下面的东西,其中 initService 获取 JSON 数据源,然后分配所有数据
angular.module('walletApp')
.run([
'InitService', function (initService) {
initService.get();
},
]);
angular.bootstrap(document, ['walletApp']);
但这会导致一堆问题。
我们如何正确加载需要通过AJAX获取数据才能运行的AngularJS应用?
答案#1
好的,据我理解,你需要在UI的任何其他部分加载之前获取JSON数据(因为这是在网站本身加载之前就需要的数据)。
所以,你不能在配置阶段创建 http,如果你在 run 阶段调用它,你必须等到主 http 调用完成(我们称之为 /site_data/)。
不要在 index.html 中使用
ng-app在
app.js文件中(function() { var initInjector = angular.injector(['ng']); var $http = initInjector.get('$http'); $http.get('/site_data/',{headers: {'Cache-Control' : 'no-cache'}}).then( function (response) { angular.module('walletApp.info', []).constant('SITE_CONF_DATA', response.data); angular.element(document).ready(function() { angular.bootstrap(document, ['walletApp']); //<-- manual bootstrapping of `ng-app` }); } ); })(); var app = angular.module('walletApp',['walletApp.info']); app.config(function(SITE_CONF_DATA){ // Bingo, you have the data }) app.run()..... app.controller... app.factory.....
这种方法有一个缺点,就是你的网站会在 http 调用解决后才加载。
更新
根据评论,您正在尝试构建一个混合应用程序,所以看看这个演示。
ngOnInit() {
// Ensure AngularJS is only bootstrapped once.
if (!angularJsBootstrapped) {
this.http.get('https://jsonplaceholder.typicode.com/todos/1').delay(5000).subscribe(res => {
angular.module('data',[]).constant('DATA',res);
this.upgrade.bootstrap(document.body, [module.name]);
setUpLocationSync(this.upgrade);
angularJsBootstrapped = true;
})
}
}
我通过在 http 解析后创建一个模块来创建了一个 constant,然后我手动引导了 angularJS 模块。
angular.module('data',[]).constant('DATA',res);像这样的东西可能对你描述的情况有帮助。
