javascript - Angular2 suscribirse entender función flecha
Intento entender las funciones flecha de TypeScript mediante el ejemplo del método subscribe de Observable en Angular 2. ¿Alguien podría explicármelo:
Tengo este código que funciona:
this.readdataservice.getPost().subscribe(
posts => { this.posts = posts; }
);
¿pero debería ser lo mismo si uso esto? Pero esto no funciona.
this.readdataservice.getPost().subscribe(
function (posts) {
this.posts = posts;
}
);
Respuesta #1
La función flecha es anónima y no enlaza su propio
this. Por lo tanto,thises elthisdel contexto actual.La función normal vincula
thisal llamador si no lo vinculamos explícitamente
Entonces
this.readdataservice.getPost().subscribe(
posts => { this.posts = posts; }
);
Puede ser
var self = this;
this.readdataservice.getPost().subscribe(
function(posts) { self.posts = posts; }
);
O
this.readdataservice.getPost().subscribe(
function(posts) { this.posts = posts; }.bind(this)
);
Respuesta #2
JS por defecto ejecuta funciones en el alcance del llamador. Si pasas una función para que sea llamada en otro lugar, this apunta al llamador. En tu código pasas la función al observable a través del método subscribe(...) y luego la función es llamada por el observable cuando se debe emitir un evento.
Si usas una función flecha, entonces this sigue apuntando a la clase donde está definida.
Una alternativa es usar .bind(this) para decirle a JS que this debe seguir apuntando a la instancia actual de la clase.
this.readdataservice.getPost().subscribe(
function (posts) {
this.posts = posts;
}.bind(this)
);
Véase también https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Functions/Arrow_functions
