访问变量从RxJS subscribe()函数声明了一个组件

Hao*_* Yu 12 javascript rxjs typescript arrow-functions angular

我能够用来this.variable访问组件的任何部分中的变量,除了在RxJS函数之外,如subscribe()catch().

在下面的示例中,我想在运行进程后打印一条消息:

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);
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

当我跑步时doSomething(),我得到了不确定.可以使用局部变量来解决此方案:

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() {

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

        runTheProcess()
        .subscribe(function(location) {
            console.log(message);
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

我想这与此有关this,但是,为什么我无法访问this.message内部subscribe()

dre*_*ore 36

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

我假设您熟悉thisJavascript中函数调用的上下文中的语义(如果没有,在线上不乏解释) - 当然,这些语义适用于第一个片段,这是唯一的原因this.message是内部未定义subscribe()那里.那只是Javascript.

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

所以,如果你更换:

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

通过:

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

你会得到你期望的结果.