从 RxJS subscribe() 函数声明一个组件的访问变量 [英] Access variables declared a component from a RxJS subscribe() function
问题描述
我可以使用 this.variable
来访问组件任何部分的变量,除了像 subscribe()
或 catch() 这样的 RxJS 函数内部代码>.
I am able to use this.variable
to access variables in any part of the component, except inside RxJS functions like subscribe()
or catch()
.
在下面的例子中,我想在运行一个进程后打印一条消息:
In the example below, 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()
时,我得到 undefined.这种情况可以使用局部变量来解决:
When I run doSomething()
, I get undefined. This scenario can be solved 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
有关,但是,为什么我无法访问subscribe()
中的this.message
?
I suppose this is related to the this
, however, why I can't access the this.message
inside the subscribe()
?
推荐答案
这与 rx 或 angular 无关,而与 Javascript 和 Typescript 有关.
This has nothing to do with rx or angular, and everything to do with Javascript and Typescript.
我假设您在 Javascript 中的函数调用上下文中熟悉 this
的语义(如果不是,则有 不乏在线解释) - 当然,这些语义适用于第一个片段,这也是 this 的唯一原因.message
在 subscribe()
里面是未定义的.那只是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.
既然我们在谈论打字稿:箭头函数是一种 Typescript 结构,旨在(部分)避免这些语义的笨拙通过词法捕获 this
的含义,意味着箭头函数中的 this
=== this
来自外部上下文.
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'
});
您会得到预期的结果.
这篇关于从 RxJS subscribe() 函数声明一个组件的访问变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!