[英]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。
B.component.ts如何知道何时更改了A.component.ts?
如何在两个组件之间设置此共享变量?
如果要在两个组件之间共享变量,请使用服务,并使用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.