Search code examples
angularangular-formsangular-event-emitter

event capture in multiple component in angular 4


i have single component called address, which rendered multiple times for home address and office address, on changing one i want to update another, so that i have written sharedService and used eventemmiter. but it capturing for same component not in another ..i am expecting 'in Address' log two times

@Injectable()
export class SharedService {
  onMainEvent: EventEmitter = new EventEmitter();
}


@Component({ ... })
export class AddressComponent {
  onMain: boolean = false;
  constructor(service: SharedService) {
    service.onMainEvent.subscribe(
      (onMain) => {
        this.onMain = onMain;
        console.log('in Address')
      }
   );
 }
updateAddress(onMain):void {
    this.service.onMainEvent.emit(onMain);
  }

}

Solution

  • You need to make your service being injected as singleton:

    for angular 6 and upper

    @Injectable({providedIn: 'root'})
       export class SharedService {
         onMainEvent: EventEmitter = new EventEmitter();
       }
    

    for lower:

    @NgModule({
      ...
      providers: [UserService],
      ...
    })
    

    More preferred way of doing such a thing is to use flux architecture such as ngrx or ngxs for angular.