0

在我的应用程序中,我有两个不同的模块 (@NgModule) 独立运行,现在我希望它们应该相互通信并共享数据。这两个模块是延迟加载的。如何将模块 1 中的服务更改反映到模块 2

4

1 回答 1

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);
    });
  }

}

于 2017-11-25T17:09:32.567 回答