我有一个组件指令,我用它来显示带有一些信息的div。
这个组件称为SitesComponent,包含在页面中。SitesComponent的主要行为是很好的,除了这样:
这是我的密码:
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或API承诺的文章,我尝试了两种方法,但都找不到解决方案.当我更新.subscribe()或.then()函数中的变量时,用户界面从未更新过
编辑:--我忘记添加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];
}
)}
}最终编辑
找到了另一个问题的解决方案,我试着关闭这个问题。
解决我问题的问题是:
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")
}
)
}
}
}发布于 2018-01-02 15:45:10
实现OnInit
import { OnInit } from '@angular/core';
export class SitesComponent implements OnInit {}https://stackoverflow.com/questions/48063654
复制相似问题