AngularBehaviorSubject 在首次加载时不起作用

问题描述 投票:0回答:1

我在

BehaviorSubject
文件中定义了一个
profile.service.ts
,其中将
false
作为初始值,并且我从
profileDialog.component.ts
函数中的
ngOnInit
组件订阅它,并将
 中的值从 
false
 更新为 
true
 home.component.ts
这个组件。

当我登录网站并加载页面时,当值从

profileDialog.component.ts
更改为
false
时,
true
组件中存在的订阅者不会订阅。

但是当我重新加载页面时,一切都会按预期进行。

profile.service.ts:

export class ProfileService {
  private displayProfileDialogSubject: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);

  public setProfileDialogBoolean(value: boolean) {
    this.displayProfileDialogSubject.next(value);
  }

  public getProfileDialog() {
    return this.displayProfileDialogSubject.asObservable();
  }
}

home.component.ts:

export class HomeComponent {
  showProfileDialog() {
    this.profileService.setProfileDialogBoolean(true);
  }
}
单击

showProfileDialog() 文件中的按钮将调用

home.component.html
函数。

profileDialog.component.ts:

ngOnInit {
  this.profileDialogSubscription = this.profileService.getProfileDialog().subscribe(isOpen => {
      if (isOpen) {
        console.log("Profile dialog will be opened.");
      }
    });
}
angular rxjs
1个回答
0
投票

请检查您的服务。如果您在服务中使用providIn:'root'和@Injectable(),则不需要将其包含在任何模块的providers数组中。由于它被视为单个实例,因此可以跨应用程序使用它,而无需在任何模块中提供它。

如果您的服务存在以下代码

@可注射({ 提供于:'root' })

然后删除模块中的providers数组中的服务类。

© www.soinside.com 2019 - 2024. All rights reserved.