gpt4 book ai didi

javascript - Angular Controller 检查服务 promise 以更新 View

转载 作者:行者123 更新时间:2023-12-03 11:12:20 25 4
gpt4 key购买 nike

我在使用 Angular Controller 和服务时遇到问题,无法让它们很好地协同工作。

我有 Parse API 可以登录,我希望 Controller 知道发生了登录失败/成功的情况,并相应地更新 View 。

我尝试从服务的 Parse 登录 promise 返回一个 bool 值,但 Controller 看不到这一点,当我设置一个等于服务函数的变量时,我得到“未定义”。

var app = angular.module('myApp', []);

app.controller('myController', ['scope', 'userService', function($scope, userService){

$scope.ctrlFunc = function(){
var login = userService.login($scope.username, $scope.password);
//$scope.username & password are defined in other section
console.log(login); //returns 'undefined'
if(login == true){
// go to other function
}
else{
// do $scope changes to view
}
};
}]);

app.service ('userService', function(){
this.login = function(){
Parse.User.logIn(username, password,{
success: function (user){
return true;
},
error: function (error){
return false;
}
})
};
});

我的 Controller 逻辑臃肿,因此我尝试将其卸载到服务中。对于 Angular 初学者来说,说起来容易做起来难......

最佳答案

您没有考虑登录行为的异步性质。您需要使用回调或使用 Angular Promise 来处理登录成功或失败。

有了 promise 机制,服务就变成了

app.service ('userService', function($q){
var defer=$q.defer();
this.login = function(){
Parse.User.logIn(username, password,{
success: function (user){
defer.resolve(true);
},
error: function (error){
defer.reject(false);
}
})
return defer.promise;
};
});

现在在 Controller 中您可以执行以下操作:

var login = userService.login($scope.username, $scope.password)
.then(function(result) { //result will be true and you can react to it.},
function(error) { //error will be true and you can react to it.})

阅读有关 Angular Promise 的内容,了解事物的工作原理。

关于javascript - Angular Controller 检查服务 promise 以更新 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27518568/

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