Search code examples
angularservicecomponentsshare

Angular 8: passing data via local service between components in seperated modules


I have this local service

  private messageSource = new BehaviorSubject('default message')
  public currentMessage = this.messageSource.asObservable();

  constructor() { }

  changeMessage(message: string) {
    this.messageSource.next(message)
  }

}

A child component inside core module

@Output('message') message= new EventEmitter<string>()
@Output('movies') movies =new EventEmitter<any>()
storedmovies:any
  constructor(private localService: LocalService, private movieService: MoviesService) { }

  ngOnInit() {
    this.movieService.getStoredMovies().subscribe(data=>{
      this.storedmovies=data
    })
    this.localService.currentMessage.subscribe(data=>console.log(data))

  }

sendMessage(){
  this.message.emit(this.storedmovies);
}

Child thtml

<button class="btn btn-danger" (click)="sendMessage()">Send Message</button>

Admin compnent inside Admin module

TS

 ngOnInit() {
    this.localService.currentMessage.subscribe(data=>console.log(data))
    console.log(this.localService.changeMessage('new message'))
  }
  receivedMessage($event) {
    console.log($event)
  }

HTML

<app-child
(message)="receivedMessage($event)"> -> not recognized

But in the appModule where the child is registred hav it in the export array

@NgModule({
  declarations: [
    //etc
    ChildComponent,
  ],
  imports: [
    /etc
  ],
  exports:[
    ChildComponent
  ],

so what I need to do to child componet be recognixe in the admin module? Do I need to import the component? I've ried alredy and it didnt worked...


Solution

  • According to the module structure you provide in your question, I understand that the idea would be:

    1. To declare and export your child component within its module (CoreModule) instead of the AppModule.

    2. And then import this module into the Admin module.

    I have created this example where you can see it working. https://stackblitz.com/edit/angular-ebetqi

    Angular docs are very good, have a look to these 2 resources related with modules and how to structure them...

    1. https://angular.io/guide/architecture-modules
    2. https://angular.io/guide/styleguide#application-structure-and-ngmodules