Bu, yazı tipinin kapsam ve değişken erişilebilirliği hakkında daha genel bir soru olabilir.Bir RxJS subscribe() işlevi içinde bileşen değişkenleri alamadı
veya catch()
gibi RxJS işlevleri dışında, bileşenlerin herhangi bir bölümünde değişkenler almak için this.variable
'u kullanabilirim. Örneğin, ben bir işlemi çalıştırdıktan sonra bir ileti yazdırmak istiyorum: Ben doSomething()
çalıştırdığınızda
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);
});
}
}
, bir tanımsız alacak. Bu, yerel bir değişken kullanarak sabitlenebilir:
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);
});
}
}
Bu this
ilgilidir varsayalım. Ancak neden subscribe()
değil doSomething()
'da this.message
'dan ileti alabilirim?
arrow işlevler https://basarat.gitbooks.io/typescript/content/docs/arrow-functions.html – basarat