我有一项服务负责在组件之间切换侧导航
表单菜单服务
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable()
export class FormMenuService {
openMenu: BehaviorSubject<any> = new BehaviorSubject<any>(null);
toggle(): void {
this.openMenu.next({ test: 'test' });
}
}
表单组件
ngAfterViewInit(): void {
this.formMenuService.openMenu.subscribe((data) => {
console.log(data);
this.sidenavMenu.open();
}
在 Toolbar.Component 中,我触发 FormMenuService
openFormMenu() {
this.formMenuService.toggle()
}
当我运行openFormMenu
时,该服务也可以工作。但在 Form.component 中,订阅没有被触发。
订阅仅在使用 null
值加载组件时触发一次,该值是 SubjectBehavior
的初始值。这意味着服务声明正在起作用。
我不知道为什么订阅在初始加载后不起作用
我也尝试过iniside ngOnInit
也不起作用
最佳答案
请验证该服务仅在提供程序中导入一次,如果该服务位于多个提供程序中,您可能会遇到此问题。
import { bootstrapApplication } from '@angular/platform-browser';
import 'zone.js';
import { TestService } from './test.service';
import { TestComponent } from './test/test.component';
@Component({
selector: 'app-root',
standalone: true,
providers: [TestService], // <- this Test service should only be added to providers once to ensure a singleton class is used!
imports: [TestComponent],
template: `
<h1>Hello from test!</h1>
<a target="_blank" href="https://angular.dev/overview">
Learn more about Angular
</a>
<app-test></app-test>
`,
})
export class App {
constructor(private testService: TestService) {}
ngAfterViewInit(): void {
this.testService.openMenu.subscribe((data) => {
console.log(data);
});
}
}
bootstrapApplication(App);
stackblitz showing this problem happening
另一种选择是直接给予
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable({
providedIn: 'root',
})
export class FormMenuService {
openMenu: BehaviorSubject<any> = new BehaviorSubject<any>(null);
toggle(): void {
this.openMenu.next({ test: 'test' });
}
}
关于javascript - Angular BehaviourSubject 仅在组件加载时触发订阅一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77699781/