我是 Angular 新手,我正在努力了解应该如何创建特定的 Promise。我还使用 typescript 进行编码。
我需要调用 Web 服务来进行身份验证,这必须分两步完成。
第 1 步
请求身份验证 key
第 2 步
使用身份验证 key 处理登录详细信息,并返回服务以检索登录用户或错误(如果不正确)
所以我创建了一个名为 AuthenticationService 的 Angular 服务 像下面这样(这当然行不通)
export class Authentication
{
$inject: string[] = ['$http'];
public Authenticate( userName: string, password: string ): ng.IHttpPromise<ApiModel.ApiResult<ApiModel.AuthenticatedUser>>
{
$http.post( "/Account/AuthenticationKey", null )
.then<ApiModel.ApiResult<string>>( result =>
{
var strKey = userName + password; //TODO: Put correct code here!
var promiseToReturn = $http.post( "/Account/Authenticate", { key: strKey })
.then<ApiModel.ApiResult<ApiModel.AuthenticatedUser>>( result =>
{
return result;
});
});
}
}
如何从返回第二个结果的身份验证方法中返回具有正确返回类型的 promise ?
最佳答案
我可以告诉你,在 JavaScript 中,因为我不熟悉 typescript 。这个想法是创建你自己的 promise 并在你想要的时候解决它。基本上
var autenticate=function(user,password) {
var defer=$q.defer();
$http.post( "/Account/AuthenticationKey", null )
.then(function(data) {
//do something on data
$http.post( "/Account/Authenticate", { key: strKey })
.then(function(result) {
defer.resolve(result)
});
})
return defer.promise;
}
关于javascript - AngularJS 中的链式 Promis,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19289965/