无法获得RxJS内部组件变量认购()函数 [英] unable to get component variables inside a RxJS subscribe() function
问题描述
这可能是有关范围和打字稿的可变辅助功能更普遍的问题。
This may be a more general question about scope and variable accessibility of typescript.
我可以使用 this.variable
来获得组件的任何部分变量,除了RxJS功能,如订阅()
或赶上()
。例如,我想在运行过程后打印的消息:
I can use this.variable
to get variables in any part of the component, except RxJS functions like subscribe()
or catch()
. For example, I want to print a message after running a process:
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的()
,我会得到的未定义。这可以通过使用一个局部变量来修正:
When I run doSomething()
, I will get an undefined. This can be fixed by using a local variable:
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.message
消息DoSomething的()订阅( )
?
I suppose this is related to this
. But why can I get message from this.message
in doSomething()
, not subscribe()
?
推荐答案
这已无关,与RX或角,一切都用JavaScript和打字稿做。
This has nothing to do with rx or angular, and everything to do with Javascript and Typescript.
我假设你熟悉这个
在Javascript中的函数调用的情况下(如果没有,还有的no解释网上)短缺 - 这些语义适用于第一个片段,当然,这是唯一的原因 this.message
在里面未定义订阅()
那里。这只是的JavaScript。
I assume you're familiar with the semantics of this
in the context of function invocations in Javascript (if not, there are no shortage of explanations online) - those semantics apply in the first snippet, of course, and that's the only reason this.message
is undefined inside subscribe()
there. That's just Javascript.
由于我们正在谈论的打字稿:
箭功能是打字稿结构,旨在(部分)回避这些语义的尴尬通过捕捉词汇的含义这个
,即这个
箭头功能=== 内这个
从外部环境。
Since we're talking about Typescript:
Arrow functions are a Typescript construct intended (in part) to sidestep the awkwardness of these semantics by lexically capturing the meaning of this
, meaning that this
inside an arrow function === this
from the outer context.
所以,如果你替换:
.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'
});
您会得到你预期的结果。
You'll get your expected result.
这篇关于无法获得RxJS内部组件变量认购()函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!