如何在不重新加载组件的情况下将更新的变量传递给另一个组件?
How to pass an updated variable to another component without reloading the component?
我不确定是否存在这样的问题,因为我不完全知道我要查找的概念是以什么命名的。
所以我有一个共享服务:
// shared.service.ts
public showLoginForm: boolean = true;
在我的 app.component 中,我使用上面的变量如下:
//app.component.ts
ngOnInit: void {
this.showLoginForm = this.sharedSrv.showLoginForm;
}
现在,在我的 login.component 中,我在不离开 app.component 视图的情况下更改服务中的变量:
// login.component.ts
login(f: ngForm){
...
this.sharedSrv.showLoginForm = false;
}
如何将 showLoginForm
的新值传递给应用程序组件?
将 showLoginForm
作为 Observable 流,类似于 shared.service.ts
private showLoginFormSubject: BehaviorSubject<boolean>;
constructor() {
this.showLoginFormSubject = new BehaviorSubject(true);
}
setShowLoginForm(show: boolean) {
this.showLoginFormSubject.next(show);
}
getShowLoginForm(): Observable<boolean> {
return this.showLoginFormSubject.asObservable();
}
现在在组件中:login.component.ts
this.sharedSrv.getShowLoginForm().subscribe(val=>this.showLoginForm=val);
更新值:
this.sharedSrv.setShowLoginForm(false);
我不确定是否存在这样的问题,因为我不完全知道我要查找的概念是以什么命名的。 所以我有一个共享服务:
// shared.service.ts
public showLoginForm: boolean = true;
在我的 app.component 中,我使用上面的变量如下:
//app.component.ts
ngOnInit: void {
this.showLoginForm = this.sharedSrv.showLoginForm;
}
现在,在我的 login.component 中,我在不离开 app.component 视图的情况下更改服务中的变量:
// login.component.ts
login(f: ngForm){
...
this.sharedSrv.showLoginForm = false;
}
如何将 showLoginForm
的新值传递给应用程序组件?
将 showLoginForm
作为 Observable 流,类似于 shared.service.ts
private showLoginFormSubject: BehaviorSubject<boolean>;
constructor() {
this.showLoginFormSubject = new BehaviorSubject(true);
}
setShowLoginForm(show: boolean) {
this.showLoginFormSubject.next(show);
}
getShowLoginForm(): Observable<boolean> {
return this.showLoginFormSubject.asObservable();
}
现在在组件中:login.component.ts
this.sharedSrv.getShowLoginForm().subscribe(val=>this.showLoginForm=val);
更新值:
this.sharedSrv.setShowLoginForm(false);