簡體   English   中英

從子組件Angular調用父組件函數,從sessionStorage實時更新變量

[英]Angular call parent component function from child component, update variable in real time from sessionStorage

代碼以 product 變量中的初始值開始,該值被設置到 sessionStorage 中。 當我觸發側面板(子組件)時,它會從 url 中的參數接收 product.name,然后該組件在 sessionStorage 中搜索並更新 product.amount 值(並將其設置為 sessionStorage)。

我試圖從子組件調用的父組件函數是 getProductStatus(); 當我更新側面板中的 product.amount 值時,我還需要同時更新父組件中的產品對象。 這就是我一直在嘗試的,提前致謝。

代碼: https : //stackblitz.com/edit/angular-ivy-npo4z7?file=src%2Fapp%2Fapp.component.html

 export class AppComponent { product: any; productReturned: any; constructor() { this.product = { name: 'foo', amount: 1 }; } ngOnInit() { this.getProductStatus(); } getProductStatus(): void { this.productReturned = this.getStorage(); if (this.productReturned) { this.product = JSON.parse(this.productReturned); } else { this.setStorage(); } } setStorage(): void { sessionStorage.setItem(this.product.name, JSON.stringify(this.product)); } getStorage() { return sessionStorage.getItem(this.product.name); } reset() { sessionStorage.clear(); window.location.reload(); } }

在這種情況下,您有兩種數據共享選項。 如果您只需要父組件中的數據:

在 child.component.ts 中:

@Output() someEvent = new EventEmitter

someFunction(): void {
  this.someEvent.emit('Some data...')
}

在父模板中:

<app-child (someEvent)="handleSomeEvent($event)"></app-child>

在 parent.component.ts 中:

handleSomeEvent(event: any): void {
  // Do something (with the event data) or call any functions in the component
}

如果您可能還需要另一個組件中的數據,您可以將服務綁定到應用程序的根目錄,並在您的應用程序中的任何不相關組件中訂閱主題。

服務:

@Injectable()
export class DataService {

  private _data = new BehaviorSubject<SnapshotSelection>(new Data());
  private dataStore: { data: any }

  get data() {
    return this.dataStore.asObservable();
  }

  updatedDataSelection(data: Data){
    this.dataStore.data.push(data);
  }
  
}

只需在接收和輸出組件的構造函數中傳遞服務。

在接收端的 ngOnInit() 中:

subscription!: Subscription
...
dataService.data.subscribe(data => {
  // Do something when data changes
})
...
ngOnDestroy() {
  this.subscription.unsubscribe()
}

然后只需在更改發生的地方使用 updatedDataSelection() 。

我在這里記錄了組件之間所有類型的數據共享:

https://github.com/H3AR7B3A7/EarlyAngularProjects/tree/master/dataSharing

以數據服務為例:

https://github.com/H3AR7B3A7/EarlyAngularProjects/tree/master/dataService

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM