使用TypeScript在ui-router中解析可以解析$ http调用的正确方法是什么?

时间:2015-05-23 22:31:25

标签: angularjs typescript angular-ui-router typescript1.4

我通过服务获得了一个简单的HTTP服务;

module shared {

    export interface IAuthService {
        isAuthenticated: () => any;
    }

    export class AuthService implements IAuthService {
        static $inject = ['$http'];

        constructor(private $http:ng.IHttpService) {
        }

        isAuthenticated():any {
            return this.$http({
                method: 'GET',
                url: 'http://localhost/auth'
            });
        }
    }

    export var app:ng.IModule = app || angular.module('shared', ['ngResource']);
    app.service('AuthService', AuthService);
}

我在路线决心中使用它;

$stateProvider.state('app', {
            url: "/app",
            abstract: true,
            templateUrl: "app/menu.html",
            controller: 'AppController',
            resolve: {
                authService: 'AuthService',
                isAuthenticated: function (authService) {
                    return authService.isAuthenticated();
                }
            }
        });

问题是,我使用HTTP响应代码来获得结果 - 如果用户通过身份验证,我会发回一些JSON数据(因此任何返回类型,直到我构建类)。如果没有,我返回HTTP / 403。

这在JS中运作正常,也许是巧合,但似乎在迁移到打字稿时,403现在停止了解决方案的死亡,应用程序只是坐在那里..有没有人碰到过这个?有更正确的方法吗?

编辑:我被问到生成的JS - .state是相同的,服务转换成了这个;

AuthService.prototype.isAuthenticated = function () {
                return this.$http({
                    method: 'GET',
                    url: this.ConfigService.apiBaseUri + '/authentication/authenticated',
                    headers: { 'Authorization': this.ConfigService.sessionId }
                });
            };

1 个答案:

答案 0 :(得分:2)

因此,回想起来的答案非常明显。被拒绝的承诺也拒绝了州的过渡。因此,当可能无法进行的$ http调用失败时,正确的解决方案是添加.then(function(data){// ...},function(){// ...})到resolve方法中的调用。就我而言;

isAuthenticated: function (authService) {
    return authService.isAuthenticated().then(function(data) { return data; }, function() { return null; });
}