使用TypeScript的AngularJS app无法调用undefined方法

时间:2013-07-10 15:02:23

标签: angularjs typescript

我是AngularJS和Web开发的新手,所以这可能是一个愚蠢的问题,但我无法弄明白。

我有我的主应用程序

/// <reference path="../../references.ts" />


angular.module("mainApp", [])
    .config(($routeProvider: ng.IRouteProvider) => {
        $routeProvider
            .when("/", {
                templateUrl: "/app/module/mainApp/partials/main.html",
                controller: AppController,
                //datacontext
                controllerAs: "dc"
            })
            .when("/login", {
                templateUrl: "/app/module/mainApp/partials/login.html",
                controller: LoginController,
                controllerAs: "dc",

            })
    })

    .run(($rootScope: ng.IRootScopeService, $location: ng.ILocationService, AuthService) => {
        $rootScope.$on("$routeChangeStart", (event, next, current) => {
            if (!AuthService.IsLoggedIn()) {
                if (next.templateUrl == "app/module/mainApp/partials/login") {
                    return;
                } else {
                    $location.path("/login");
                }
            }
        });
    })

我的身份验证服务看起来像这样。永远不会调用构造函数中的警报

/// <reference path="../../../references.ts" />

class AuthService {
    constructor(public ServiceManager: IServiceManager, public TokenHandler) {
        alert("I am a constructor");
    }

    Login(loginRequest: Models.LoginRequest, successCallback) {
        var params = {
            username: loginRequest.username,
            password: loginRequest.password
        };

        var service = this.ServiceManager.CallGetWithoutToken("http://url...", params);
        service.success((data, status, headers, config) => {
            this.TokenHandler.SetToken(data.replace(reg, ''));
        });
    };

    IsLoggedIn() {
        return this.TokenHandler.GetToken() != undefined;
    }
}

angular.module("mainApp").factory("AuthService", () => AuthService.prototype);

最后我的TokenHandler就是这个

class TokenHandler {
    token = undefined;

    constructor() {
    }

    ClearToken() {
        this.token = undefined;
    };

    SetToken(sessionToken: string) {
        this.token = sessionToken;
    };

    GetToken() {
        return this.token;
    };
}

angular.module("mainApp").factory("TokenHandler", () => TokenHandler.prototype);

所有我的.ts文件都在references.ts中,我已将.js文件添加到index.html。

当我运行这个时,我得到一个错误,无法调用未定义的方法“GetToken()”

不应该AngularJS在AuthService中注入我的TokenHandler吗?

1 个答案:

答案 0 :(得分:1)

这些界限几乎肯定是错的;你有什么打算在这里传递.prototype?

angular.module("mainApp").factory("TokenHandler", () => TokenHandler.prototype);

angular.module("mainApp").factory("AuthService", () => AuthService.prototype);

我想你想要:

angular.module("mainApp").factory("TokenHandler", () => new TokenHandler());

angular.module("mainApp").factory("AuthService", () => new AuthService());