【发布时间】:2016-01-07 04:34:29
【问题描述】:
我可以使用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?
【问题讨论】:
标签: javascript angular typescript rxjs arrow-functions