【问题标题】:TypeScript, Angular 1.x: How do lambda functions affect property resolution?TypeScript,Angular 1.x:lambda 函数如何影响属性解析?
【发布时间】:2016-11-14 03:08:18
【问题描述】:

编辑:

我能够解决这个问题,但我不知道为什么。所以,我修改了这个问题以反映我现在的立场。我将旧问题留作参考。

新问题:

将 lambda 函数更改为旧式函数修复了 TS 编译器无法在 $state 上找到属性的问题。我不知道为什么会这样。所以,我现在的问题是……

lambda 函数如何影响属性解析?还有..

如何确定何时使用 lambda 函数与旧式函数?

通过恢复到旧式函数来修复属性解析:

下面的老问题:

标题:TypeScript,Angular 1.x:$state.go 不存在——但它在同一个文件的其他地方存在

我正在将 Angular 1.5 应用程序从 vanilla JS 转换为 TypeScript。我遇到了一个奇怪的问题,$state 上的方法 go 存在且不存在于同一类中。

(在下图中可能很难看到,但请注意,在第二个this.$state.go 中,go 有一个红色下划线,因为编译器认为该属性不存在)

这是完整的课程:

export class LogoutAndInfoController implements ILogoutAndInfo {
    public memberInfo: Object;
    static $inject = [
        '$http', '$state', 'AuthService', 'API_ENDPOINT', 'UserInfoService'
    ];

    constructor(private $http: angular.IHttpService, private $state: angular.ui.IStateProvider,
    private AuthService: AuthService, private API_ENDPOINT: IAPI_ENDPOINT, private UserInfoService: UserInfoService) {
        this.memberInfo = {};
    }

    destroySession(): void {
        this.AuthService.logout();
    }

    getInfo(): void {
        this.$http.get(this.API_ENDPOINT["url"] + '/memberinfo').then(function (result) {
            this.memberInfo = result.data["user"];
            this.$state.go('login');
        });
    }

    logout(): void {
        this.AuthService.logout().then((result: any) => {
            this.UserInfoService.resetUser();
            this.$state.go('login');
        });
    }
}

我对 Angular 框架中的 TS 和 TS 都很陌生。所以,请让我知道在我们调试之前是否需要查看任何其他代码。

【问题讨论】:

    标签: javascript angularjs typescript


    【解决方案1】:

    这实际上是由于 this 的行为...与您可能使用过的大多数其他语言相比,在 Javascript 中的表现很奇怪。

    在您的第一个示例中,您调用$http.get()。由于 this 在 JS 中的工作方式,get() 函数将被调用,this 被设置为任何 this.$http 在这种情况下。这就是时髦开始的地方。 this 仅在您调用对象上的方法时设置,并且在调用新函数时保持不变。这意味着当$http.get() 调用您的回调时,this 仍设置为$http,因此$state 不存在。

    这就是为什么你会到处看到var self = this; 的模式。它允许您绑定到您所知道的this,因此以下内容将起作用:

    var self = this;
    this.$http.get(..., function() {
        self.$state.go()
    });
    

    另一方面,Lambda 函数的绑定方式不同。所谓的“箭头函数”没有自己的 this 上下文,因此在创建它们的函数中关闭了 this,因此它们可以按预期工作。

    更多来源:

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

    https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions#No_binding_of_this

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-30
      • 1970-01-01
      • 2016-08-14
      • 2017-04-26
      相关资源
      最近更新 更多