gpt4 book ai didi

javascript - Ionic、Cordova、Phonegap 加载消息

转载 作者:行者123 更新时间:2023-11-28 15:41:03 26 4
gpt4 key购买 nike

我正在使用 ionic 框架和 angular.js 开发一个应用程序,我发现我的加载消息在我的内容加载之前就消失了 - 这是一些示例代码

$scope.validateUser = function () {
var email = this.user.email;
var password = this.user.password;
if(!email || !password) {
$rootScope.notify("Please enter valid credentials");
return false;
}
$rootScope.show('Please wait.. Authenticating');
API.signin({
email: email,
password: password
}).success(function (data) {
$rootScope.setToken(email); // create a session kind of thing on the client side
$rootScope.hide();
$window.location.href = ('#/database/list');
}).error(function (error) {
$rootScope.hide();
$rootScope.notify("Invalid Username or password");
});
}

“#database/list”是从 RESTful API 中获取的,并且在应用程序中渲染页面之前身份验证消息就会消失。

我是否正确地认为我应该将 $rootScope.hide() 移动到 $window.location.href 线下方,或者它是否更险恶(即我收到警告 $rootScope.hide() 已贬值并且我应该使用 $ionicLoading.hide();

我对 Angular 和应用程序开发(主要是 PHP 开发)非常陌生,因此我们将不胜感激。

最佳答案

尽量不要将对象附加到 $rootScope,而是使用服务来存储全局可访问的数据。此外,您还需要了解 Angular 如何使用 promises解决远程数据调用。

基本思想是调用 Controller 中的函数,该函数又调用登录服务来对用户进行身份验证。调用后会发生 4 件事。

  1. 显示加载屏幕
  2. LoginService.login 进行远程调用(通过 Promise)来验证用户身份
  3. Controller 等待,直到 LoginService.login promise 得到解决
  4. 一旦 promise 解决,用户对象就会使用收到的 token 进行更新,并且加载屏幕将被隐藏。

Demo

演示使用超时代替 $http 调用来解决延迟问题。

查看:

  <ion-content ng-controller="AppCtrl" has-header="true" padding="true">
<div class="card">
<div class="item">
<button ng-click="login()">Login</button>
<div ng-show="user.token">
Logged in with token: {{user.token}}
</div>
</div>
</div>
</ion-content>

Controller :

.controller('AppCtrl', function($scope, $ionicLoading, LoginService) {
$scope.user = {};

$scope.login = function(usr, pwd) {
var result = LoginService.login(usr, pwd);

// show loading screen
$ionicLoading.show({template: 'Logging In...'});

result.then(function(data) {
$ionicLoading.hide();
$scope.user.token = data.token;
});


return result;
}
});

登录服务:

.service('LoginService', function($q, $timeout) {
return {
login: function() {
var defer = $q.defer();

$timeout(function() {
defer.resolve({token: new Date().getTime()});
}, 3000);


// replace timeout function with actual $http call
// the $http call will return a promise equivelant to
// defer.promise;
//$http({
// url: '//myloginurl',
// params: {usr: 'myusr', pwd: 'mypwd'}
//}).success(function(data) {
// // presume data contains json {token: some token}
// defer.resolve(data);
//}).error(function(){
// defer.resolve();
//});

return defer.promise;
}
}
});

关于javascript - Ionic、Cordova、Phonegap 加载消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23733931/

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