I have subscribed to a ReplaySubject and trying to unsubscribe in ngOnDestroy method. When I move away from the subscription component and come back to same component wihtout emitting the data, again its getting subscribed. May I know how can I solve this issue?
Shared.service.ts
import { Injectable } from '@angular/core';
import { TestCase } from './test-case-form/test-case.model';
import { Subject } from 'rxjs/Subject';
import { ReplaySubject } from 'rxjs/ReplaySubject';
@Injectable({
providedIn: 'root'
})
export class SharedService {
testCasesChanged = new Subject<TestCase[]>();
private startedEditing = new ReplaySubject<number>();
public startedEditing$ = this.startedEditing.asObservable();
setData(index) {
console.log("setData called", index);
this.startedEditing.next(index);
}
}
a.component.ts
export class TestFormComponent implements OnInit, OnDestroy {
@ViewChild('f') testForm : NgForm;
subscription: Subscription;
editIndex: number;
editMode = false;
editedTestCase: TestCase;
private testCases: TestCase[]= [];
ngOnInit() {
this.subscription = this.sharedService.startedEditing$
.subscribe((index: number) => {
console.log("Subscribed");
this.editIndex = index;
this.editMode = true;
this.editedTestCase =
this.sharedService.getTestCase(this.editIndex);
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
startedEditing
during the second time? – Caramiriel