[英]Angular 10 - View doesn't update when model is modified
Angular 10.1.6、TypeScript 4.0.5
你好
在我的 webapp 中,我有 3 个组件。
组件 A存储一个Array<Image>
export class ComponentParentA implements OnInit {
images: Array <Image> ;
addImageToList(newImage: Image) {
this.images.push(newImage)
}
}
组件 C显示图像列表。
export class ComponentChildC implements OnInit {
@Input() images: Array <Image>;
}
组件 C 从组件 A html 模板调用,如下所示:
<ComponentChildC [images]="images"></ComponentChildC>
B组负责联系我的API,加一张之前选好的图。 API返回一个Image object,对应我的model。 组件发出图像,因此 ComponentA 将返回的图像添加到其数组中(调用 addImageToList)
addImage 是 this.http.post ( HttpClient ) 的 Observable 返回
export class ComponentChildB implements OnInit, AfterViewInit {
@Output() eventCreateImage : EventEmitter<Image>;
addImage(data) {
this.service.addImage(data).subscribe((image) => {
this.eventCreateImage.emit(image)
})
}
}
组件 A 像这样调用组件 B:
<ComponentChildB (eventCreateImage)="addImageToList($event)"></ComponentChildB>
当我单击按钮时,组件 B 添加图像。 此点击触发addImage
function。 所有组件都正常工作,图像保存在我的服务器上。 API 返回图像,后者正确存储在组件 A 的数组中。但是,组件 C 的视图没有更新,新创建的图像也没有出现。 如果我再次单击该按钮,则会存储一个新图像。 这一次,我之前看不到的之前的图像正确显示了。 新图没有。
我希望图像直接出现。
我在 web 上看到了类似的问题。
addImageToList
function 中用this.images = this.images.concat(newImage)
替换this.images.push(newImage)
。 它不起作用。console.log(this.images)
时,我看到列表已正确更新。 但是图像仍然没有出现。 所以我尝试调用诸如 markForCheck 和 detectChanges 之类的ChangeDetectorRef方法来通知组件发生了变化,但是没有成功。如果您知道我的问题可能来自哪里,如果您能帮助我,我将不胜感激
我没有测试,但我认为这是导致策略检测的原因。 您可以尝试 3 种不同的解决方案(我现在无法测试,但通常它会起作用)。
PS:对不起我的英语
1/ 在您的 object @Component 在您的组件中添加 changeDetection
@Component({
selector: 'app-component',
template: `...`,
changeDetection: ChangeDetectionStrategy.OnPush
})
然后在你的 function addImageToList() 替换你的代码
addImageToList(newImage) {
this.images = [...this.images, newImage]
}
2/ 在您的组件 C 中,将您的 @Input 替换为
@Input() set images(value: Array <Image>) {
myImages = value
}
html 中的属性绑定将是 myImages 在此上下文中
3/ 您可以使用服务 ChangeDetectorRef 手动更改策略检测。 在您的构造函数组件 A 中添加此服务,然后在 function 中添加:
constructor(
private cd: ChangeDetectorRef
){}
addImageToList(newImage: Image) {
this.images = [...this.images, newImages];
this.cd.markForCheck();
}
如果此解决方案不起作用,请查看 Angular 中的检测策略文档或尝试将 1 和 2 混合在一起
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.