Last active
October 23, 2016 18:48
-
-
Save aitorjs/599faaf3c0b0a207d3fe2321edba2cd6 to your computer and use it in GitHub Desktop.
Solución a problema de ámbito de variables dentro de funciones con bind(this)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// PROBLEMA. Bind error. No reconoce this.products de la linea 15. | |
import { Component } from '@angular/core'; | |
import ApiWrapperService from './lib/apiWrapper.service'; | |
import { Product } from './entitys/product' | |
export class AppComponent { | |
products: Array<Product>; | |
constructor(api: ApiWrapperService) { | |
api | |
.get('products') | |
.then(function(products) { | |
console.log(products); | |
this.products = products | |
}); | |
} | |
} | |
// ES5. Bind-eando this. Permite poder usar bind dentro de la función de la linea 33. | |
// Recordemos que cada función tiene su ámbito de variable. | |
import { Component } from '@angular/core'; | |
import ApiWrapperService from './lib/apiWrapper.service'; | |
import { Product } from './entitys/product' | |
export class AppComponent { | |
products: Array<Product>; | |
constructor(api: ApiWrapperService) { | |
api | |
.get('products') | |
.then(function(products) { | |
this.products = products | |
}.bind(this)); | |
} | |
} | |
// ES6. Las arrow functions bind-ean this por lo que el problema se soluciona. | |
// Probado con typescript. Sin el necesitariamos babel, traceour, browserify, webpack... | |
import { Component } from '@angular/core'; | |
import ApiWrapperService from './lib/apiWrapper.service'; | |
import { Product } from './entitys/product' | |
export class AppComponent { | |
products: Array<Product>; | |
constructor(api: ApiWrapperService) { | |
api | |
.get('products') | |
.then(products => { | |
console.log(products); | |
this.products = products | |
}); | |
// OR | |
// api | |
// .get('products') | |
// .then(products => this.products = products); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment