AngularJS – 控制器不等待条件语句中的服务返回值
发布时间:2020-12-17 17:48:23 所属栏目:安全 来源:网络整理
导读:我正在尝试将登录用户重定向远离登录页面,如果他们尝试在应用程序中访问它.与登录页面关联的控制器 – Login_controller调用授权服务中的函数 – Authorisation_service.isLoggedIn().如果此服务返回true,则应将用户重定向到登录的概述页面. 通过登录到控制
我正在尝试将登录用户重定向远离登录页面,如果他们尝试在应用程序中访问它.与登录页面关联的控制器 – Login_controller调用授权服务中的函数 – Authorisation_service.isLoggedIn().如果此服务返回true,则应将用户重定向到登录的概述页面.
通过登录到控制台,我可以看到在服务返回true之前,条件语句已经声明从服务返回的值是未定义的.之后服务确实返回true,但为时已晚. 如何让控制器的条件语句等待服务的返回值? Authorise_service.js myApp.factory('Authorise',['User','$http','$location','$rootScope',function( User,$http,$location,$rootScope ) { return { isLoggedIn: function() { if( ((sessionStorage.username && sessionStorage.authKey) && (sessionStorage.username !== "null" && sessionStorage.authKey !== "null")) || ((localStorage.username && localStorage.authKey) && (localStorage.username !== "null" && localStorage.authKey !== "null" )) ) { if( sessionStorage.username ) { var usernameLocal = sessionStorage.username; var authKeyLocal = sessionStorage.authKey; } else { var usernameLocal = localStorage.username; var authKeyLocal = localStorage.authKey; } //pass to server var user = User.query({ usernameLocal: usernameLocal,authKeyLocal: authKeyLocal },function(user) { if( user.loginSuccess === 1 ) { return true; } else { return false; } }); } else { return false; } } }; }]); Login_controller.js myApp.controller( 'Login_controller',function( Authorise,$scope,$location ) { if( Authorise.isLoggedIn() === true ) { console.log("Authorise.isLoggedIn() = true"); $location.path('/teach/overview'); } }); 解决方法
Smk是对的.您可能正在尝试依赖服务器尚未返回的数据. “然而”这里是关键问题,因为很可能你的数据是从服务器中正确获取的,你只是想在它们准备好之前参考结果!要检查这是否是事实,只需在User.query(…)回调中添加console.log(user).
Smk向您指出了正确的方法 – 使用PROMISE API代替.基本上,promise是一个对象,当结果从服务器准备就绪时,您可以进一步使用它来执行某些操作.为了说明这一点: function myFunc() { var result = false; // You are calling async request to the server,so the execution won't wait for the // results. It will simply fire server request and proceed to next lines. serverCall(function(srvResponse){ result = srvResponse.everythingIsGood; // This will be called after the whole method finishes! }); return result; // This will MOST PROBABLY return 'false' all the times. } 这是一个正确的方法: function theRealLogicYouWantToDo(result) { if (result) { // ... } else { // ... } } serverCall(function(srvResponse) { theRealLogicYouWantToDo(srvResposne.everythingIsGood); }); 关于JQUERY的所有这些This is nice tutorial.它不仅用于服务器调用,还用于JS中的其他几个地方.很高兴学习它. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |