2013-07-10 40 views
1

我是AngularJS和Web开发的新手,因此这可能是一个愚蠢的问题,但我无法弄清楚。使用TypeScript的AngularJS应用程序无法调用未定义的方法

我有我的主要的应用程序

/// <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。

当我运行此我得到一个错误未定义

Should'nt AngularJS不能调用方法“为gettoken()”注入我的AuthService TokenHandler?

回答

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()); 
相关问题