我有这项服务:
monApp.service('serviceEtatConnexion', function ($http) {
this.getEtatConnexion = function () {
return $http.get('backend/backend.php?action=get_etat_connexion');
};
});
后端php直接调用时返回该值:
{"statuslogin":1}
在我的 angularjs 路由中,我想得到这个值,像这样测试这个值:
resolve:{
"check":function($window,serviceEtatConnexion,$location){
var u = serviceEtatConnexion.getEtatConnexion();
console.log('u est egal a ' +u);
console.log(u.$$state.statuslogin);
alert(JSON.stringify(u, null, 4));
/* if( u!= '{"$$state":{"status":0}}' ){
alert("ok");
}else{
alert("Vous devez vous identifier pour utiliser cette partie");
$window.location.href ='http://liseo.lan/dev/login.phtml?mlog=&domain=stuff';
} */
}
}
绝对没有办法获取 statuslogin json 值,看看我已经尝试过的所有方法。我总是在控制台中看到“未定义” 我不明白为什么。
有关信息,这是我的 php 函数,它正确编码 json:
function get_etat_connexion(){
session_start();
include_once( "../../../globprefs.php" );
include_once( "../../../manage_session.php" );
$http_form_vars = count( $_POST ) > 0 ? $_POST :
( count($_GET) > 0 ? $_GET : array("") );
if(USER&PASSWORD){
$reponse['statuslogin']=1;
echo(json_encode($reponse));
}
else{
$reponse['statuslogin']=0;
echo(json_encode($reponse));
}
}
即使这样也不起作用并返回未定义:
var statuslogin = $http.get('backend/backend.php?action=get_etat_connexion'); console.log('statuslogin est equal a ' +statuslogin);
最佳答案
$http
服务返回 promise ,这意味着仅调用该函数不会返回任何内容,因为 promise 尚未得到解决。看看下面的代码片段
resolve:{
"check":function($window,serviceEtatConnexion,$location, $q) {
var deferred = $q.defer();
serviceEtatConnexion.getEtatConnexion()
.then(function(result) {
if (result.statusLogin === 1) {
// Everything is okay, resolve the promise with the result
deferred.resolve(result);
} else {
// Something went wrong, not logged in. Reject the promise
deferred.reject(result);
}
});
return deferred.promise;
}
}
然后您可以在 if
语句中添加任何代码来处理错误。一个常见的约定是监听 $stateChangeError
事件并在该监听器内处理重定向等。
关于javascript - 无法将 JSON 从服务获取到 angularJs 路由中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42155943/