【发布时间】:2021-07-30 16:11:24
【问题描述】:
我们可以使用 Behavior Subject 访问多个组件中的变量,但我刚刚发现我们可以访问其他组件中的变量,只需在我们希望访问它们的文件的构造函数中将它们声明为“公共”。
行为主体是在组件之间传递变量值的首选方式,还是可以使用 public 代替/使用“public”有什么缺点?
方法一:行为主体
// To use Behavior Subject:
// First, add the .service's name to the constructor() of both components.
// Next, add this code to your .service file:
// //-------------------------------------------------------------------------------
// public loginPageErrorMessageSource = new BehaviorSubject<any>(null); // The (null) tells it to initialize the listener to "null"
// changeLoginPageErrorMessage(message: any) { // To change the message / variable value, call this function from one of your .components (you can't call this function from within the same .service file)
// this.loginPageErrorMessageSource.next(message)
// }
// loginPageErrorMessageChanges = this.loginPageErrorMessageSource.asObservable();
// -------------------------------------------------------------------------------
然后将其放入您希望访问消息更改的组件的 ngOnInit() 中:
this.loginPageErrorMessageChanges.subscribe(data => {
if(data !== undefined) {
console.log(data)
}
})
方法二:在构造函数中公开文件
-假设我有一个 sign-in.component.ts 文件,我希望访问 change-password.component.ts 中变量的值。
我只是把它放在 change-password.component.ts 的 constructor() 中:
constructor(public signInComponent: SignInComponent) { }
然后在change-password.component.ts的ngOnInit()中打印出来:
ngOnInit() {
console.log(this.signInComponent.variableIwantToAccess)
}
【问题讨论】:
-
您能否提供一些示例代码来说明您如何访问组件之间的变量?
-
我已经更新了我的问题
标签: angular rxjs components behaviorsubject