0

in my application, I have two different module (@NgModule) running independently and now I want they should communicate to each other and share data.the two modules are lazy loaded.how to reflect the service changes in module1 to module2

1 Answers1

1

Create SharedModule and Inject SharedService in providers array as shown below

import { CommonModule } from '@angular/common';

import { SharedService } from './shared.service';

@NgModule({
    imports: [
        FormsModule,
        CommonModule
    ],
    exports: [

    ]
})
export class SharedModule {
    static forRoot(): ModuleWithProviders {
        return {
            ngModule: SharedModule,
            providers: [SharedService]
        };
    }
}

And Create SharedService as shown below with bookTitleOrAuthorSearchEvent EventEmitter

import { Injectable, Inject, EventEmitter } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { Subject } from 'rxjs/Subject';


@Injectable()
export class SharedService {


    public bookTitleOrAuthorSearchEvent = new EventEmitter<string>();


   }

and Inject SharedModule to app.module as for forRoot as shown below

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { NoopAnimationsModule } from '@angular/platform-browser/animations';

import { SharedModule } from './modules/shared/shared.module';



@NgModule({
  declarations: [
    AppComponent,
    //..
  ],
  imports: [
    //..
    SharedModule.forRoot()
  ],
  providers: [
  //...
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

and Inject sharedService in any of your module's component and an instance of sharedService is available in all components of any modules and you can use EventEmitter or BehaviorSubject to emit the data and capture it where is required as shown below

import { Component, OnInit, DoCheck, ViewEncapsulation } from '@angular/core';
import { SharedService } from './../shared/shared.service';

@Component({
  selector: 'app-anytime-lib',
  templateUrl: './anytime-lib.component.html',
  styleUrls: ['./anytime-lib.component.css'],
  encapsulation: ViewEncapsulation.None
})
export class AnytimeLibComponent implements OnInit, DoCheck {

  constructor(private sharedService: SharedService) {

  }

  ngOnInit() {
    this.clearSession();
  }
  clearSession() {
    // this.sharedService.removeSessionItem('userInfo');
  }

  ngDoCheck() {   
    this.sharedService.bookTitleOrAuthorSearchEvent.subscribe((data) => {
      console.log('Emitted data', data);
    });
  }

}