簡體   English   中英

Angular 5在兩個組件之間共享變量

[英]Angular 5 share variable between two components

我要在兩個組件中聲明一個共享變量,並且希望這些組件具有共享值。 我想知道是否可以做到這一點。

A.html

...
<button (click)="sendInfo(a,b,c)" > </button>
...

B.html

...
<div *ngIf="showData" > {{loadData()}} </div> 
...

A.component.ts

...
showData = false;
sendInfo(a: string, b:string, c:string) {
//calling webservice
showData = true;
}
...

B.component.ts

...
showData = false;
//when button from A.html clicked
showData = true;

因此,在B.component.ts中,如果單擊A.html中的按鈕,我想將showData設置為true。

  1. B.component.ts如何知道何時更改了A.component.ts?

  2. 如何在兩個組件之間設置此共享變量?

如果要在兩個組件之間共享變量,請使用服務,並使用ReplaySubject觀察:

export class Service {
   sharedVariable$ = new ReplaySubject(1);
   updateValue(value) {
       this.sharedVariable$.next(value);
   }
}

在組件中注入服務:

class Component {
   constructor(public service: Service) {}
}

並在html中使用:

<span>{{service.sharedVariable$ | async}}</span>
<button (click)="service.updateValue(55)">set 55</button>

這比使用組件綁定和未來證明共享變量要好得多。

暫無
暫無

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

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