我有一个在应用程序级别注册的中央服务,其任务是保持并发送所有组件的模型的最新状态:
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';
import { Feature } from '../models/Feature.model'
@Injectable()
export class CentralService {
private feature = new Subject<Feature>();
feature$= this.feature.asObservable();
emitToFeature(feature: Feature) {
this.feature.next(feature);
}
}
从我的一个组件中我发出一个功能并显示一个mdl对话框(来自angular2-mdl):
import { Component, OnInit } from '@angular/core';
import { FeatureComponent } from '../feature/feature.component'
import { MdlDialogService } from 'angular2-mdl';
import { CentralService } from '../services/central.service';
@Component({
...
providers:[TaskListService]
})
export class TaskListComponent implements OnInit {
feature: any=[];
constructor(
public dialogService: MdlDialogService,
private centralService: CentralService){
}
addToFeature(value, task){
if(value==true){
this.feature.push(task)
this.centralService.emitToFeature(this.feature)
}
else{
let index: number = this.feature.indexOf(task)
if (index !== -1) {
this.feature.splice(index, 1);
this.centralService.emitToFeature(this.feature)
}
}
}
openDialog(){
this.dialogService.showCustomDialog({
component: FeatureComponent,
animate: true,
isModal: true,
styles: {'width': '800px', 'max-height':'500px' ,'overflow-y':'scroll'},
clickOutsideToClose: true
})
}
}
该对话框基本上显示了FeatureComponent:
import { Component, OnInit, AfterContentInit } from '@angular/core';
import { CentralService } from '../services/central.service';
@Component({
...
})
export class FeatureComponent implements OnInit, AfterContentInit {
constructor(
private centralService: CentralService
) {
}
ngOnInit() {
}
ngAfterContentInit(){
this.centralService.feature$.subscribe(
feature => {
console.log('In Feature component ', feature)
}
)
}
}
对话框正确加载并显示FeatureComponent的模板,但不知何故它不从中央服务获取功能。我尝试在ngOnInit()和构造函数中编写它,但没有帮助。
对话框插座位于app.html:
<app-header></app-header>
<dialog-outlet></dialog-outlet>
<router-outlet></router-outlet>
注意:没有在ngAfterContentInit()中编写的控制台语句。我做错了什么?