I am facing an issue with accessing the brandName
variable from a sibling component within the same module. I have attempted to achieve this using a BehaviorSubject
.
Although I am able to receive the updated brandName
in my service, my component still displays the default message.
This is how my Service file looks:
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable()
export class DataService {
private messageSource = new BehaviorSubject('default message');
currentMessage = this.messageSource.asObservable();
constructor() { }
changeMessage(message: string) {
console.log('service sent: ' + message);
this.messageSource.next(message);
}
}
The console successfully logs the updated message here.
However, when attempting to update the variable in Order component, it still shows the "default message".
Order.component.ts:
import {DataService} from '../services/data.service';
...
export class OrderComponent implements OnInit {
...
constructor(...private data: DataService)
...
this.data.currentMessage.subscribe(message => this.brandName = message);
console.log('brandname');
console.log(this.brandName);
It continuously prints out 'default message'.
Only their common parent module app.module.ts
includes the DataService
provider.
Edit
I have also attempted to access the variable from a third component using:
this.data.currentMessage.subscribe(message => this.brandName = message);
In this case, the brandname does get updated, but the intended component still displays nothing, despite both components being at the same level.
Additionally, I tried recreating the service as follows
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class DataService {
private data: string;
setOption(value) {
this.data = value;
console.log('service sent: ' + value + ' and data ' + this.data);
}
getOption() {
console.log('service returned');
console.log(this.data);
return this.data;
}
However, the problem persists - while the service receives the updated value, the third component can access it, but the main component that the service was meant for continues to show the default value.