new in angular 2 and facing a problem here. Have an API which loads a js file in my project. The problem is, I have to use this js file and is not in my control to change it, basically, this js file has few methods which call an API via AJAX and return an array, but the way it returns it quite old fashion. All I need is to update the view as soon the data comes in, tried many ways, but still cant get it worked. Any ideas how can I bind and update the view?
import {Component, AfterContentInit} from "@angular/core"; import {IProduct} from "./product"; import {ProductService} from "./product.service"; declare var ExpressLibraryLoader: any; @Component({ selector: 'pm-products', moduleId: module.id, templateUrl: 'product-list.component.html', styleUrls: ['product-list.component.css'] }) export class ProductListComponent implements AfterContentInit{ pageTitle: string = 'Product List'; listFilter: string = ''; products = []; errorMessage: string; constructor(private _productService: ProductService) { } ngAfterContentInit(): void{ //this._productService.getProducts(). // subscribe(products => this.products = products, error => this.errorMessage = <any>error); ExpressLibraryLoader.initialise({ platformKey: 'xxx', brandID: 20, libraryUrl: "http://localhost/xxxxcx/", domainLaunchUrl: "http://localhost/xcxcxc/", success: function (ExpressLibrary) { let parameters = { languageCode: 'en', gameProviderID: [7], success: function (response) { if (response.Status === "Success") { //response.Result.Games.map(response => this.products = response); this.products = response.Result.Games; console.log(this.products) } else { } }, error: function () { } }; ExpressLibrary.games.getDesktop(parameters); } }); } }
Looks like you need to use arrow function, this
reference does not point to your class instance:
success: function (ExpressLibrary) { ... }
//change to
success: (ExpressLibrary) => { ... }
// or, quite funny you mentioned it
success: function (ExpressLibrary) { ... }.bind(this)
I found out the issue, it seems that this
in
success: function (response) {
if (response.Status === "Success") {
this.products = response.Result.Games;
console.log(this.products)
} }
has a different scope. So, solution is obvious and dead easy:
var that = this;
var parameters =
{
//various parameters
success: function(response){
if (response.Status === "Success") {
that.products = response.Result.Games;
}
},
error: function () {
}
};
ExpressLibrary.games.getDesktop(parameters);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.