繁体   English   中英

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

[英]Best practice writing AngularJS controller in Typescript

我真的是AngularJS和Web开发的新手,并且对C#和C ++更有经验。 因此,我尝试使用Typescript。

我现在正在使用控制器,并且出现了一些奇怪的行为。 当使用下面的代码中的登录功能时,a会出现问题,那就是未在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")
  }
}

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

提前致谢。

then()的上下文中, this不是控制器。 你必须抓住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");
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM