[英]Why isn't my input bound property changing in my angular child component?
我有一個有兩個孩子的父組件。
父組件有一個屬性,它實際上是一個像這樣的字典:
dict = {a: 0, b: 0, c: 0};
我進行輸入綁定,以便兩個子組件都可以訪問dict
。
<app-child-a [dict]="dict"></app-child-a>
<app-child-b [dict]="dict"></app-child-b>
孩子 A 更改了dict
的屬性
@Input() dict: any;
someFunctionInChildA() {
this.dict.b = 1;
}
我可以驗證父組件是否知道此更改。
ngAfterInit() {
setInterval(() => console.log(this.dict), 1000);
}
這將打印0
秒,直到someFunctionInChildA
被觸發,然后打印1
秒。
這是我的問題:孩子 B 似乎沒有看到變化。 這是孩子 B 的一些代碼
@Input() dict: any;
ngAfterInit() {
setInterval(() => console.log(this.dict), 1000);
}
即使在someFunctionInChildA
被觸發之后,這someFunctionInChildA
一直打印0
s。
我不明白屬性綁定是如何工作的嗎? 或者更有可能我在其他地方有一個愚蠢或不相關的錯誤?
正如你在這里看到的: https : //stackblitz.com/edit/angular-7-master-nxys2f?file=src/app/hello.component.ts
有問題的代碼工作正常。 但是..這是一個非常糟糕的做法。 因為這種遠距離突變會產生難以推理的代碼和難以理解的錯誤。 我猜您的實際應用程序要復雜一些,而且您可能不小心在某處破壞了引用。 這就是為什么你應該使用共享服務模型和 rxjs 在組件之間共享信息:
@Injectable()
export class DictService {
private dictSource = new BehaviorSubject({a: 0, b: 0, c: 0})
dict$ = this.dictSource.asObservable()
setDict(dict) {
this.dictSource.next(dict)
}
}
然后注入您的組件並訂閱:
constructor(private dictService: DictService) {
this.dictSub = this.dictService.dict$.subscribe(dict => this.dict = dict) // don't forget to unsubscribe!
}
並使用該服務進行更新:
someFunctionInChildA() {
this.dict.b = 1;
this.dictService.setDict(this.dict)
}
我已經解決了這個問題,我懷疑其他人會覺得這很有用,因為這是一件罕見的事情......
幾天前,我實際上做了一個服務,可以將dict
保存和更新到 Firebase,這將通過 rxjs 與我的組件同步。 但是我留下了一些舊的邏輯(即dict
由組件而不是服務管理的邏輯)。
我會將其標記為正確答案,但真正歸功於 @bryan06 對此類應用程序正確模式的良好解釋。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.