gpt4 book ai didi

javascript - ionic 加载数据 THEN 显示主页

转载 作者:行者123 更新时间:2023-11-30 09:45:52 26 4
gpt4 key购买 nike

在我的 Ionic 应用程序中,我在应用程序打开时加载所有数据(通过 http 请求)。

我想确保我的所有 http 请求都已完成,然后显示主页。与此同时,想法是显示加载屏幕。

最好的方法是什么?

angular.module('App.Common', [])
.service('myData', function($http, API_URL) {
this.initData = function() {
self.getDataType2(); //calls http request
self.getDataType2(); //calls http request
self.getDataType3(); //calls http request
self.getDataType4(); //calls http request
self.getDataType5(); //calls http request
self.getDataType6(); //calls http request
};
});


angular.module('App.Home', [])

.controller('Ctrl', function(myData) {
myData.initData();
});

在我的 home.html 中,当 initData() 没有完成时,我会显示一个加载页面。

我知道加载部分会用这段代码

  $ionicLoading.show({
content: 'Loading',
animation: 'fade-in',
showBackdrop: true,
maxWidth: 200,
showDelay: 0
});

但是如何/何时使用

$ionicLoading.hide();

任何帮助将不胜感激

最佳答案

首先您需要确保所有请求都得到解决

为了实现这个目标,您可以使用内置的 $q 服务。您最终会得到这样的服务:

angular.module('App.Common', [])
.service('myData', function($q, $http, API_URL) {
this.initData = function() {
return $q.all([
self.getDataType1(); //calls http request
self.getDataType2(); //calls http request
self.getDataType3(); //calls http request
self.getDataType4(); //calls http request
self.getDataType5(); //calls http request
self.getDataType6(); //calls http request
]).then(function(data1, data2, data3, ...) {
return { data1: data1, ... };
});
};
});

这将为您提供一个 initData 方法,该方法在完成所有 http 请求后返回一个 promise 对象。

然后为了防止在数据准备好之前加载 View ,您需要配置状态以使用解析数据。

angular
.module('App', ['ionic', 'App.Common'])
.config(function($stateProvider) {
$stateProvider.state('home', {
url: '/home',
views: {
'': {
templateUrl: '/path-to-your-state-view',
controller: 'HomeController'
}
},
resolve: {
data: function($ionicLoading, myData) {
$ionicLoading.show();

return myData.initData().finally($ionicLoading.hide);
}
}
});
});

最后,您必须告诉您的 Controller 等待解析依赖项加载。

angular
.module('App')
.controller('HomeController', function($scope, data) {
$scope.data = data;
});

我对您的应用做了很多假设(状态、模块名称等),但我希望这是一个起点。

所有相关来源是:

angular $qui-router state resolves

关于javascript - ionic 加载数据 THEN 显示主页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38919822/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com