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();
}
}
when i check the output i am not able to get the emission of product$
i understand that refresh will fire then it should switch to product$ which emits 5 but i am not seeing that output, which is it not emitting values even thought i have used behaviour subject?
even when i subscribe to this.testService.product$ from ngonit not getting any data, event after calling next() method of productSubject, why is this the case?
CodePudding user response:
As per the code you just pasted is likely that the cause is because product$
is a derivation of refreshSubject
rather than productSubject
.
Hence you're emitting new values into the productSubject
but that isn't wired to anything