Search code examples
angularangular-materialangular8angular-componentsangular-changedetection

How can i get variable changes in a service file automatically updates in the parentcomponent?


enter image description here

I have a parent component, where I am calling a service that has a dialog open method. There I am opening the dialog component. Now, in my dialog component, I have a form and add data button, when I add I am posting the data to the service as an event. After add data button clicked I should not close my dialog is should keep open. My new form data in the dialog service is updated. But how can I send that event to the parent component automatically? it should detect the changes and update the variable in the parent component.

Thanks in advance. Please provide code/reference/connect to me to solve this problem.


Solution

  • If you really want to use a service, then you need a Subject into your service, and a getter which will return your subject as observable. With this solution, every subscribers will be noticed everytime your subject will change.

    service

    subject = new Subject<any>();
    
    get subject$(): Observable<any> {
      return this.subject.asObservable();
    }
    

    parent

    constrcutor(private service: YourService) {
      this.service.subject$.subscribe(console.log);
    }
    

    dialog

    
    constructor(private service: YourService) {}
    
    submit(): void {
      this.service.subject.next(this.form.value); // Replace this.form.value by what you want
    }