如何在angular2中的两个模块之间共享服务

时间:2017-06-21 06:31:56

标签: angular2-services angular2-modules

在我的应用程序中,我有两个不同的模块(@NgModule)独立运行,现在我希望他们应该相互通信并共享数据。这两个模块是延迟加载的。以反映module1到module2中的服务更改< / p>

1 个答案:

答案 0 :(得分:1)

在providers数组中创建SharedModule和Inject SharedService,如下所示

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

使用bookTitleOrAuthorSearchEvent EventEmitter创建SharedService,如下所示

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


   }

并将SharedModule注入到app.module和forRoot,如下所示

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 { }

并在任何模块的组件中注入sharedService,并且任何模块的所有组件都可以使用sharedService实例,您可以使用EventEmitter或BehaviorSubject发送数据并将其捕获到需要的位置,如下所示

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

}