我可以使用 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()
时,我得到了 undefined。这种情况可以使用局部变量来解决:
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);
});
}
}
我想这与 this
有关,但是,为什么我无法访问 subscribe()
中的 this.message
?
最佳答案
这与 rx 或 angular 无关,与 Javascript 和 Typescript 无关。
我假设您在 Javascript 函数调用的上下文中熟悉 this
的语义(如果不熟悉,则有 no shortage of explanations online )- 这些语义当然适用于第一个片段,这是 this.message
在 subscribe()
中未定义的唯一原因。那只是 Javascript。
既然我们在谈论 Typescript:
Arrow functions是一个 Typescript 结构,旨在(部分)通过词法捕获 this
的含义来回避这些语义的尴尬,这意味着箭头函数中的 this
=== this
来自外部上下文。
所以,如果你替换:
.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'
});
您将获得预期的结果。
关于javascript - 从 RxJS subscribe() 函数访问声明为组件的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34647449/