In my setup, there is a component named Database along with a Service called DatabaseService
.
The current database status is stored in a BehaviourSubject
and I need to access this status from the App Component.
To achieve this, I subscribe to the BehaviourSubject
within the app.component.ts
.
When I fetch the initial value using the BehaviourSubject, everything works as expected. However, if I trigger the .next()
method from the database component, the updated value is not reflected in the app component.
I attempted moving the call to .next()
inside a method within the database service, but unfortunately, it did not solve the issue.
Database.component.ts
@Component({
selector: 'app-database',
templateUrl: './database.component.html',
styleUrls: ['./database.component.scss'],
providers: [DatabaseService]
})
export class DatabaseComponent implements OnInit, OnDestroy {
...
constructor(
private databaseService: DatabaseService,
) {
}
ngOnInit(): void {
...
}
updateDatabaseStatus(): void {
this.databaseService.databaseStatus.next(this.StatusId.value);
}
ngOnDestroy(): void {
...
}
}
database.service.ts
@Injectable({
providedIn: 'root'
})
export class DatabaseService {
public databaseStatus = new BehaviorSubject<DatabaseStatus>(DatabaseStatus.Open);
constructor(private api: ApiService) {
this.getSettingsDatabaseStatus().subscribe(data => {
this.databaseStatus.next(data[0].statusId);
});
}
public getSettingsDatabaseStatus(): Observable<Status> {
...
}
public updateCurrentDatabaseStatus(status: DatabaseStatus): void {
this.databaseStatus.next(status);
}
}
app.component.ts
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit, OnDestroy {
public databaseStatus = 'Open';
constructor(public router: Router,
private _api: ApiService,
private databaseService: DatabaseService) {
}
ngOnInit(): void {
this.databaseService.databaseStatus.subscribe(status => {
this.databaseStatus = DatabaseStatus[status];
});
}
ngOnDestroy(): void {
...
}
}