15

または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()と、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アクセスできないのはなぜですか?this.messagesubscribe()

4

2 に答える 2