繁体   English   中英

更新Angular2中的视图

[英]Update the view in Angular2

角度2新,面临问题。 有一个API在我的项目中加载一个js文件。 问题是,我必须使用这个js文件而不是我的控制来改变它,基本上,这个js文件有很少的方法通过AJAX调用API并返回一个数组,但它返回它的方式很旧。 我需要的只是在数据进入后立即更新视图,尝试了很多方法,但仍然无法使其工作。 任何想法如何绑定和更新视图?

 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); } }); } } 

看起来你需要使用箭头功能, this引用并没有指向你的类实例:

 success: function (ExpressLibrary) { ... }
 //change to
 success: (ExpressLibrary) => { ... }
 // or, quite funny you mentioned it
 success: function (ExpressLibrary) { ... }.bind(this)

我发现了这个问题,似乎就是this问题

success: function (response) {
           if (response.Status === "Success") {
             this.products = response.Result.Games;
             console.log(this.products)
           } } 

有不同的范围。 因此,解决方案显而易见且简单易行:

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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM