Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subject.subscribe not firing in ngOnInit

I have defined the subject in my service.ts The onEditItem() in detail.component.ts passes the value of id in .next() and the Subject is subscribed in new.component.ts But the subscription is not working. Subscription is done in ngOnInit in new.component.ts

The value of id is successfully passed in onEditItem() but subscription is not working. I've tried doing console.log check inside subscription. But nothing is printed in console.

in details.component.html

<a class="btn btn-primary" (click)="onEditItem()" routerLink="/new">Edit</a>

in details.component.ts

  onEditItem(){this.contactService.startedEditing.next(this.id);}

in contactService.ts

export class ContactService {
  startedEditing =new Subject<number>();
}

in new.component.ts

ngOnInit() {
  this.subscription = this.contactService.startedEditing.subscribe(
    (index: number) => {
      console.log(index);

      this.editedItemIndex = index;
      console.log(this.editedItemIndex);
      this.editMode = true;
      this.editedItem = this.contactService.getContacts(index);

      this.editForm.setValue({
        name: this.editedItem.name,
        address: this.editedItem.address
      })
    }
  );
} 

I expected that the form which is defined in new.component.html should be initialized with the value from details component but the subscription is not working in ngOnInit.

like image 246
Sonali Avatar asked Sep 15 '25 10:09

Sonali


1 Answers

Subjects need to emit the value in order to the observers to act upon the event.

This means you have to either click on your Div, or switch to a BehaviorSubject, which returns the last value of the stream at subscription.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!