加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

typescript – 无法在RxJS subscribe()函数中获取组件变量

发布时间:2020-12-17 07:53:44 所属栏目:安全 来源:网络整理
导读:这可能是关于打字稿的范围和变量可访问性的更一般的问题. 我可以使用this.variable来获取组件任何部分的变量,除了像subscribe()或catch()这样的RxJS函数.例如,我想在运行进程后打印一条消息: import {Component,View} from 'angular2/core';@Component({ se
这可能是关于打字稿的范围和变量可访问性的更一般的问题.

我可以使用this.variable来获取组件任何部分的变量,除了像subscribe()或catch()这样的RxJS函数.例如,我想在运行进程后打印一条消息:

import {Component,View} from 'angular2/core';

@Component({
    selector: 'navigator'
})
@View({
    template: './app.component.html',styles: ['./app.component.css']
})
export class AppComponent {
    message: string;

    constructor() {
        this.message = 'success';
    }

    doSomething() {
        runTheProcess()
        .subscribe(function(location) {
            console.log(this.message);
        });
    }
}

当我运行doSomething()时,我将得到一个未定义的.这可以通过使用局部变量来修复:

import {Component,styles: ['./app.component.css']
})
export class AppComponent {
    message: string;

    constructor() {
        this.message = 'success';
    }

    doSomething() {

        // assign it to a local variable
        let message = this.message;

        runTheProcess()
        .subscribe(function(location) {
            console.log(message);
        });
    }
}

我想这与此有关.但是为什么我可以从doSomething()中的this.message获取消息,而不是subscribe()?

这与rx或angular无关,而与Javascript和Typescript有关.

我假设您在Javascript函数调用的上下文中熟悉了它的语义(如果没有,有no shortage of explanations online) – 当然,这些语义适用于第一个片段,这就是this.message在内部未定义的唯一原因订阅()那里.那只是Javascript.

既然我们在谈论Typescript:
Arrow functions是一个Typescript构造,旨在(部分地)通过词汇捕获这个语义的含义来回避这些语义的尴尬,这意味着这个内部的箭头函数===来自外部上下文.

所以,如果你更换:

.subscribe(function(location) {
        //this != this from outer context 
        console.log(this.message); //prints 'undefined'
    });

通过:

.subscribe((location) => {
     //this == this from the outer context 
        console.log(this.message); //prints 'success'
    });

你会得到你期望的结果.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读