Angular 8:在分离的模块中的组件之间通过本地服务传递数据

问题描述 投票:0回答:1

我有这个本地服务

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

  constructor() { }

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

}

核心模块内的子组件

@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>

管理模块内的管理组件

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

但是在将子项注册到的appModule中,将其包含在导出数组中

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

所以我需要对子对象做些什么才能在管理模块中得到认可?我需要导入组件吗?我干了Alredy,但没有成功...

angular service components share
1个回答
1
投票

根据您在问题中提供的模块结构,我知道这个想法是:

  1. 而是在其模块(CoreModule)中声明并导出子组件AppModule的。

  2. 然后将此模块导入到管理模块。

我创建了this example,您可以在其中看到它的工作。https://stackblitz.com/edit/angular-ebetqi

Angular文档非常好,请看一下这两个与模块相关的资源以及如何构造它们...

  1. https://angular.io/guide/architecture-modules
  2. https://angular.io/guide/styleguide#application-structure-and-ngmodules
© www.soinside.com 2019 - 2024. All rights reserved.