Angular 10.1.6,TypeScript 4.0.5
你好
在我的 web 应用程序中,我有 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>
Component B 负责联系我的API,添加之前选择的图片。 API 返回一个 Image 对象,它对应于我的模型。组件发出图像,因此 ComponentA 将返回的图像添加到其数组中(调用 addImageToList)
addImage 是 this.http.post (HttpClient)
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
函数。所有组件都正常工作,图像保存在我的服务器上。 API 返回图像,后者正确存储在组件 A 的数组中。但是,组件 C 的视图没有更新,新创建的图像也没有出现。如果我再次单击该按钮,则会存储一个新图像。这一次,我之前看不到的先前图像正确显示。新图片没有。
我希望图片直接出现。
我在网上看到了类似的问题。
this.images.push(newImage)
函数中用 this.images = this.images.concat(newImage)
替换 addImageToList
。它不起作用。console.log(this.images)
时,我看到列表已正确更新。但是图像仍然没有出现。因此,我尝试调用 ChangeDetectorRef 方法(例如 markForCheck 和 detectChanges)来通知组件发生了更改,但没有奏效。如果你知道我的问题可能来自哪里,如果你能帮助我,我将不胜感激
答案 0 :(得分:1)
我没有测试,但我认为这是策略检测的原因。您可以尝试 3 种不同的解决方案(我现在无法测试,但通常会起作用)。
PS:对不起我的英语
1/ 在你的对象 @Component 中添加 changeDetection 在你的组件中
@Component({
selector: 'app-component',
template: `...`,
changeDetection: ChangeDetectionStrategy.OnPush
})
然后在您的函数 addImageToList() 中将您的代码替换为
addImageToList(newImage) {
this.images = [...this.images, newImage]
}
2/ 在你的组件 C 中用
替换你的@Input@Input() set images(value: Array <Image>) {
myImages = value
}
html 中的属性绑定在这个上下文中将是 myImages
3/ 您可以使用 ChangeDetectorRef 服务手动更改策略检测。在构造函数组件 A 中添加此服务,然后在函数中添加:
constructor(
private cd: ChangeDetectorRef
){}
addImageToList(newImage: Image) {
this.images = [...this.images, newImages];
this.cd.markForCheck();
}
如果此解决方案不起作用,请查看 Angular 中检测策略的文档或尝试将 1 和 2 混合在一起