[英]How to manage objects efficiently between components in Angular?
我是 Angular 的新手,从这个论坛学到了很多东西。 我有一个如下场景 组件 1 - 在表单提交组件 2 上创建 ObjectA 并将其传递给组件 2 - 对 ObjectA 进行更改并发送回 Component1(我正在使用 ngOnChange 事件来监听对象中的更改) HTML 已更新在 Component 基于更改
少量代码片段组件 1
Object1: Array<SomeInterface>;
@Input() Obj: Object;
@Output() Search: EventEmitter<any> = new EventEmitter<any>();
OnSubmit() {
this.Submit.emit(this.Obj);
}
ngOnChanges(changes: SimpleChanges): void {
this.Object1 = this.Obj
}
组件 2
@Input() Obj: Array<SomeInterface> = [];
Submit(valueEmitted: Payload) {
// Changes made to object
}
我正在研究 Angular 13
正如上面评论中提到的,这是一种您可以潜在地组织您的 2 个组件的方式,这甚至消除了传递某些过滤器的需要或需要
基本上在上面,您的组件 1 和组件 2 是“哑组件”,它们只是基于 @Input() 显示 UI 并在 @Output() 上引发事件
您的组件 3 在这里完成所有繁重的工作并处理数据,这应该消除了在 comp 1 和 2 之间传递一些数据的需要,并解决了我之前表达的一些 CD 问题
- - 编辑 - -
@山姆·K
import { Injectable } from '@angular/core';
import { BehaviorSubject, Subject } from 'rxjs';
import { PuppiesModule } from './puppies.module';
import { Puppy } from './puppy.model';
@Injectable({ providedIn: PuppiesModule })
export class PuppiesStoreService {
// Make _puppiesSource private so it's not accessible from the outside,
// expose it as puppies$ observable (read-only) instead.
// Write to _puppiesSource only through specified store methods below.
private readonly _puppiesSource = new BehaviorSubject<Puppy[]>([]);
// Exposed observable (read-only).
readonly puppies$ = this._puppiesSource.asObservable();
constructor() {}
// Get last value without subscribing to the puppies$ observable (synchronously).
getPuppies(): Puppy[] {
return this._puppiesSource.getValue();
}
private _setPuppies(puppies: Puppy[]): void {
this._puppiesSource.next(puppies);
}
addPuppy(puppy: Puppy): void {
const puppies = [...this.getPuppies(), puppy];
this._setPuppies(puppies);
}
removePuppy(puppy: Puppy): void {
const puppies = this.getPuppies().filter(p => p.id !== puppy.id);
this._setPuppies(puppies);
}
adoptPuppy(puppy: Puppy): void {
const puppies = this.getPuppies().map(p =>
p.id === puppy.id ? new Puppy({ ...p, ...{ adopted: true } }) : p
);
this._setPuppies(puppies);
}
}
这将是一个很好的示例,其中服务正在处理状态但也进行 api 调用。
您可以调整为:
providedIn: 'root'
这是您可能想要查看的另一个资源https://dev.to/avatsaev/simple-state-management-in-angular-with-only-services-and-rxjs-41p8
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.