app.component.ts
import { Component, OnInit } from '@angular/core';
import { of } from 'rxjs';
import { TestService } from './test.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
posts = [
{ id: 1, name: 'chethan' },
{ id: 2, name: 'rohan' },
{ id: 3, name: 'sai' },
{ id: 4, name: 'yashas' },
];
constructor(private readonly testService: TestService) {}
getPosts() {
return of(this.posts);
}
ngOnInit(): void {
this.testService.myData$.subscribe((data) => {
console.log('from mydata');
console.log(data);
});
// this.testService.mysecondData$.subscribe((data) => {
// console.log('from secondata');
// console.log(data);
// });
this.testService.refresh();
this.testService.emitProduct(3);
}
}
test.service.ts
import { Injectable } from '@angular/core';
import {
BehaviorSubject,
map,
Subject,
switchMap,
switchMapTo,
tap,
} from 'rxjs';
@Injectable({
providedIn: 'root',
})
export class TestService {
private refreshSubject = new Subject<void>();
refresh$ = this.refreshSubject.asObservable();
private productSubject = new BehaviorSubject<number>(1);
product$ = this.refreshSubject.asObservable();
mysecondData$ = this.product$.pipe(
tap(() => console.log('coming to mysecondata')),
map(() => 5)
);
myData$ = this.refresh$.pipe(
tap(() => console.log('myData before switchmap got refresh pipe')),
switchMap(() => this.mysecondData$),
tap(() => console.log('myData after switchmap bypassed refresh pipe'))
);
emitProduct(data: number) {
this.productSubject.next(data);
}
refresh() {
this.refreshSubject.next();
}
}
the observable product$ is not emitting values as expected even when using a behavior subject. This issue occurs despite the use of refresh to switch to product$ which emits 5. The ngoninit subscription does not receive any data even after calling next() on productSubject. Why might this be happening?