I'd like to access the Observable's value coming from a Service in two different components.
This is how I'm trying to do it:
// My service holding on Observable and initialising it with a value of 1,
// then resetData() creates a new Observable with a value of 0.
@Injectable({
providedIn: 'root',
})
export class DataService {
data$;
constructor() {
this.data$ = of(1);
}
getData() {
return this.data$;
}
resetData() {
this.data$ = of(0);
}
}
Then I try to call resetData()
in cmp1
Component but the new value is not there.
@Component()
class cmp1 implements OnInit {
data$: Observable<number>;
data: number;
constructor(private dataService: DataService) {}
ngOnInit() {
this.data$ = this.dataService.getData();
this.data$.subscribe((value) => (this.data = value));
console.log(this.data); // should be 1
}
doStuff() {
this.dataService.resetData();
console.log(this.data); // should be 0
}
}
I also try to access that same value in a different component and the value is also not there:
@Component()
class cmp2 implements OnInit {
data$: Observable<number>;
data: number;
constructor(private dataService: DataService) {}
ngOnInit() {
this.data$ = this.dataService.getData();
this.data$.subscribe((value) => (this.data = value));
console.log(this.data); // should be 1
}
doStuff() {
this.dataService.resetData();
console.log(this.data); // should be 0
}
}
There are two questions here to answer this fully:
- How to access a value of the Observable coming from a Service in a Component?
- How to access a value of the Observable coming from a Service in two different Components?