我是Angular承诺的新手,并且真的想要了解它。
我有一个控制器(MainController
)尝试通过myAuthSrv.authUser
验证用户..简单的用户名和密码。在.success
,我正在通过myCookieSrv.createCookie
创建Cookie。
创建Cookie成功后我想要做的就是拨打其他服务 - myAuthSrv.validateUser
控制器:
app.controller('MainController', function($scope, $http, myCookieSrv, myAuthSrv) {
myAuthSrv.authUser($scope.data)
.success(function (data, status, headers, config) {
var cookieName = 'myCookieName';
myCookieSrv.createCookie(cookieName, Id, 1);
//////////////////////////////////////////////
//.then(console.log("call promise here!!!"))
//.catch(error)
//////////////////////////////////////////////
}
})
.error(function (data, status, headers, config) {
$scope.err = "Something has gone wrong";
})
});
myCookieSrv :
app.service('myCookieSrv', function() {
return {
createCookie : function(cookieName, Id, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = cookieName+"="+Id+expires+"; path=/";
},
readCookie : function(cookieName) {
var nameEQ = cookieName + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
}
});
成功执行myCookieSrv.createCookie
后,我想从validateUser
致电myAuthSrv
:
app.service('myAuthSrv', function($http) {
this.authUser = function() {
return $http({
method: 'POST',
url: 'some url',
data: {},
headers: {'Content-Type': 'application/json'}
});
}
this.validateUser = function() {
return $http({
method: 'POST',
url: 'some url',
data: {},
headers: {'Content-Type': 'application/json'}
});
}
}
答案 0 :(得分:4)
创建cookie后,您无需创建承诺。只需将控制器更改为:
app.controller('MainController', function($scope, $http, myCookieSrv, myAuthSrv) {
myAuthSrv.authUser($scope.data)
.then(function () {
var cookieName = 'myCookieName';
myCookieSrv.createCookie(cookieName, Id, 1);
})
.then(function () {
return myAuthSrv.validateUser();
})
.then(function () {
//success
}, function () {
$scope.err = "Something has gone wrong";
})
});
答案 1 :(得分:0)
做这样的事情
var promise = loginService
.logincall($scope.credentials);
promise
.then(
function(payload) {
//write your code (payload is the data returned)
});
答案 2 :(得分:0)
这应该有所帮助。
app.controller('MainController', function($scope, $http, myCookieSrv, myAuthSrv) {
myAuthSrv.authUser($scope.data)
.success(function (data, status, headers, config) {
var cookieName = 'myCookieName';
myCookieSrv.createCookie(cookieName, Id, 1);
myAuthSrv.validateUser()
.success(function(){
//Auth Success
})
.error(function(){
//Error in auth
});
}
})
.error(function (data, status, headers, config) {
$scope.err = "Something has gone wrong";
})
});