访问变量从RxJS subscribe()函数中声明了一个组件
Access variables declared a component from a RxJS subscribe() function
我可以使用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);
});
}
}
当我运行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);
});
}
}
我想这与this
有关,但为什么我不能访问subscribe()
内部的this.message
?
这与rx或angular无关,一切都与Javascript和Typescript有关。
我假设您熟悉Javascript中函数调用上下文中this
的语义(如果不熟悉,在线上不乏解释)——当然,这些语义适用于第一个代码段,这也是this.message
在subscribe()
中未定义的唯一原因。这只是Javascript。
既然我们谈论的是打字:箭头函数是一种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'
});
你会得到预期的结果。
作为@drewmoore答案的替代方案,如果您希望拥有外部功能,您可以执行:
.subscribe((location) => dataHandler(location), (error) => errorHandler(error));
....
const dataHandler = (location) => {
...
}
通过将errorHandler
函数外部化,它可以在多个地方使用(即订阅)。通过使用as(fat)箭头函数,您的代码将捕获"this"上下文(如@Drewmoore的回答中所讨论的)。
缺少的是编写以下内容的能力,以及像箭头函数一样处理的能力。以下操作将隐式传递参数。不幸的是,AFAIK无法捕获this
上下文(也许可以使用bind
来实现这一点,尽管这会使代码总体上更加冗长)。
.subscribe(dataHandler, errorHandler);
这太简洁了!但是,如果需要上下文的话,唉,这是行不通的。
- 如何在react js中将值从一个组件发送到另一个组件
- 我的shareService在angular 2中发送值工作正常,但当我渲染我的另一个组件时,会获得默认值
- 聚合物是一个框架而不是一个库.如何模块化地使用web组件
- Angular2将组件方法导入到另一个组件中
- 有没有一个Nodejs库可以序列化和反序列化命名组件的路径(比如URL路径名)
- 如何向onClick事件处理程序传递一个接受参数的函数,并且仍然将该函数绑定到组件's”;这个“;上下文
- 如何在另一个组件中获取指令/组件实例
- Vue.js获取组件中的一个元素
- 制作一个高阶组件,用TypeScript实现反应中继和反应路由器的交互操作
- reactjs-redux,是否可以有一个由2个组件使用的状态
- 无法将react组件作为属性传递给另一个组件
- 在React中将方法从一个组件移动到另一个组件,并且仍然可以在原始组件中使用
- Angular 2,在没有直接关系的两个组件之间共享一个对象
- 在另一个文件夹中显示React组件
- 有没有一条清晰的路径,我可以实现一个在 ScalaJS + React 中广泛使用上下文的 React 组件
- 如何从一个组件访问另一个组件的状态
- 如何创建一个组件,我可以设置在 Angular 2 中的属性中获取 URL 数据
- 是否有一个 API 来控制火狐附加组件 SDK 中的下载
- Vue.js从另一个组件获取数据
- bind():您正在将一个组件方法绑定到该组件.React会自动为您执行此操作