在Typescript中编写AngularJS控制器的最佳实践

时间:2014-02-18 19:15:27

标签: javascript angularjs typescript

我是AngularJS和Web开发的新手,在C#和C ++方面经验丰富。 因此我尝试使用Typescript。

我正在制作一个控制器,并且有一些奇怪的行为。 当使用类似下面代码中的login-function时出现问题,那就是在then语句中没有定义服务sessionService和userDataService。 它可以在当时之前和之后访问。

class UserController {
  scope: UserControllerScope;
  location: ng.ILocationService;
  sessionService: SessionService;
  userDataService: UserDataService;

  constructor($scope: UserControllerScope,
              $location: ng.ILocationService,
              userDataService: UserDataService,
              sessionService: SessionService){
    this.scope = $scope;
    this.location = $location;
    this.userDataService = userDataService;
    this.sessionService = sessionService;
  }

  loginUser(username: string, pw: string) {
    var foundUser;
    console.log(this.sessionService);
    console.log(this.userDataService);
    console.log("Got into LoginUser");

    this.userDataService.getUserAsync(username, pw).then(function(foundUserFromDb) {
      console.log(this.sessionService);
      console.log(this.userDataService);
    });

    console.log(this.sessionService);
    console.log(this.userDataService);
    this.location.path("views/projects.html")
  }
}

是否有一种方法需要注入自定义服务,以便它们可以在类中的任何位置访问,或者您有更好的方法来处理服务和控制器的注入?

提前致谢。

1 个答案:

答案 0 :(得分:3)

this上下文中的

then()不是控制器。您必须将this捕获到另一个变量self中。如果您使用箭头函数,TypeScript将为您执行此操作...

loginUser = (username: string, pw: string) => {
    var foundUser;
    console.log(this.sessionService);
    console.log(this.userDataService);
    console.log("Got into LoginUser");

    this.userDataService.getUserAsync(username, pw).then(foundUserFromDb => {
        console.log(this.sessionService);
        console.log(this.userDataService);
    });

    console.log(this.sessionService);
    console.log(this.userDataService);
    this.location.path("views/projects.html")
}

编译的JavaScript看起来应该是这样的......

var _this = this;
this.loginUser = function (username, pw) {
    var foundUser;
    console.log(_this.sessionService);
    console.log(_this.userDataService);
    console.log("Got into LoginUser");

    _this.userDataService.getUserAsync(username, pw).then(function (foundUserFromDb) {
        console.log(_this.sessionService);
        console.log(_this.userDataService);
    });

    console.log(_this.sessionService);
    console.log(_this.userDataService);
    _this.location.path("views/projects.html");
};