Angular 4:API调用后更新模板变量[重复]

问题描述 投票:1回答:1

这个问题在这里已有答案:

我有一个Component-directive,用于显示带有一些信息的div。

此组件称为SitesComponent,包含在页面中。 SitesComponent的主要行为很好,除此之外:

  • 我有一个API调用后端,我返回一些数据,后端调用执行得很好,我收到的信息,但变量没有在模板上更新

这是我的代码:

import { Component } from '@angular/core';
import { MyApi } from '../../myapi';

@Component({
  selector: 'sites-component-widget',
  templateUrl: './sites-component.html',
  styleUrls: ['./sites-component.scss'],
})
export class SitesComponent {
    data: any = [];
    constructor(private api: MyApi}

    ngOnInit() {
        var _ = this
          this.api.company_sites(this.companyId).subscribe(
            response => {
                //this.data = response; 
                this.data = [1,2,3]; 
            },
            error => {
              console.log("error")
            }
          )
        }        
    }
}

我尝试使用收到的响应更新变量数据,并使用静态数据。 UI永远不会随API调用内的更改而更新。

我正在使用角度http客户端:

import { HttpClient } from "@angular/common/http";

但它既不起作用也不起作用

  • 我做错了什么?

我读到了使用API​​的observable或promises,我尝试了两种方式,但是找不到解决方案......当我在.subscribe()或.then()函数中更新变量时,我的UI永远不会更新

编辑:我忘了添加我的HTML,但到目前为止只有3行:

<div class="sites-online-widget">
    **{{data}}**
</div>

我的问题摘要:

如果我这样做,变量将在模板上更新

ngOnInit() {
    this.data = [1,2,3,4]
}

但是当我这样做时,模板上的变量没有更新:

ngOnInit() {
    var _ = this
      this.api.company_sites(this.companyId).subscribe(
        response => {
            this.data = [1,2,3]; 
        }
      )}        
}

Final Edit

找到了另一个问题的解决方案,我试图关闭这个。

解决我的问题的问题是:

Angular 2 View will not update after variable change in subscribe

3个基本步骤:

// Import ChangeDetectorRef
import { ChangeDetectorRef } from '@angular/core';

// Add ChangeDetectorRef to constructor
constructor(private cd: ChangeDetectorRef) {}

// Call markForCheck at the end of the subscribe function
this.cd.markForCheck();

我的代码结束了:

import { Component } from '@angular/core';
import { MyApi } from '../../myapi';

// 1
import { ChangeDetectorRef } from '@angular/core';

@Component({
  selector: 'sites-component-widget',
  templateUrl: './sites-component.html',
  styleUrls: ['./sites-component.scss'],
})
export class SitesComponent {
    data: any = [];
    constructor(
      private api: MyApi,
      // 2
      private cd: ChangeDetectorRef}

    ngOnInit() {
        var _ = this
          this.api.company_sites(this.companyId).subscribe(
            response => {
                this.data = response; 
                // 3
                this.cd.markForCheck()
            },
            error => {
              console.log("error")
            }
          )
        }        
    }
}
angular angular2-template angular2-observables
1个回答
0
投票

实现OnInit

import { OnInit } from '@angular/core';

export class SitesComponent implements OnInit {}
© www.soinside.com 2019 - 2024. All rights reserved.