Chained Promis in angularjs

Chained Promis in angularjs

本文关键字:angularjs in Promis Chained      更新时间:2023-09-26

我是角度的新手,我正在努力了解如何创建一个特定的承诺。我也使用打字稿进行编码。

我需要调用 Web 服务来进行身份验证,这必须分 2 个步骤完成。

步骤 1

请求身份验证密钥

步骤 2

使用身份验证密钥处理登录详细信息,并返回服务以检索登录用户或错误(如果不正确(

所以我创建了一个名为AuthenticationService的角度服务如下所示(这当然不起作用(

  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;
                    });
            });
        }
    }
如何从返回

第二个结果的身份验证方法返回具有正确返回类型的承诺?

我可以告诉你,因为我不熟悉打字稿。这个想法是创造你自己的承诺,并随时解决它。基本上

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;
}

then函数应始终返回另一个承诺或返回值。最终的then函数应返回一个值,该值将传播到顶部。

相关文档可以在这里找到:https://github.com/kriskowal/q

注意:Angular的承诺实现是基于kriskowal的q。

这是文档的相关部分:

如果 promiseMeSomething 返回一个承诺,该承诺稍后会实现 返回值,第一个函数(履行处理程序(将是 使用值调用。但是,如果承诺我某事函数 稍后被抛出的异常拒绝,第二个函数( 拒绝处理程序(将被调用,但有异常。

在您的情况下,您应该执行以下操作

export class Authentication
{
    $inject: string[] = ['$http'];
    public Authenticate( userName: string, password: string ): ng.IHttpPromise<ApiModel.ApiResult<ApiModel.AuthenticatedUser>>
    {
     return $http.post( "/Account/AuthenticationKey", null )
        .then<ApiModel.ApiResult<string>>( result =>
        {
            var strKey = userName + password; //TODO: Put correct code here!
            return $http.post( "/Account/Authenticate", { key: strKey })
                .then<ApiModel.ApiResult<ApiModel.AuthenticatedUser>>( result =>
                {
                    return result;
                });
        });
    }
}

请注意,在要调用的$http.posts之前有两个返回值。Angular 中的所有$http方法都返回一个 promise,这意味着您不需要显式创建另一个 promise。