子组件无法通过服务订阅EventEmitter

时间:2017-08-10 10:50:59

标签: angular

订阅组件" pop-list.component.ts" :

import { Component, OnInit } from '@angular/core';
import { ChildCommService } from '../child-comm.service';

@Component({
 selector: 'app-pop-list',
 templateUrl: './pop-list.component.html',
 styleUrls: ['./pop-list.component.css'],
 providers: [ChildCommService]
})

export class PopListComponent implements OnInit {
 recievedItem: any;
 constructor(private _childService: ChildCommService) { }
 ngOnInit() {

 this._childService.popItemSelected
 .subscribe(
 (itemToPop) => {
 this.recievedItem = itemToPop;
 }
 );
 }
}

订阅组件HTML:

<hr style="width: 300px;">
<h3>Popped Content</h3>
<div style="border: 2px; background-color:lightgrey ; width:300px;">
 <ul>
 <li>{{recievedItem}}</li>
 </ul>
</div>

服务&#34; ChildCommService.service.ts&#34;:

import { Injectable, EventEmitter } from '@angular/core';

@Injectable()
export class ChildCommService {
 popItemSelected = new EventEmitter<any>();
 constructor() { }
}

发射器组件&#34; details.component.ts&#34;:

import { Component, OnInit, Input, EventEmitter, Output } from '@angular/core';
import { ChildCommService } from '../child-comm.service';

@Component({
 selector: 'app-details',
 templateUrl: './details.component.html',
 styleUrls: ['./details.component.css'],
 providers: [ChildCommService]
})
export class DetailsComponent implements OnInit {
 @Input() list;
 @Output() selectedItem= new EventEmitter();
 @Output() reduceCount= new EventEmitter();
 itemToPop ='';
 onSelect(item: string): void {
 this.selectedItem.emit(item);
 }
 constructor(private _CommService: ChildCommService ) { }
 popItem(item){
 this.itemToPop = item;
 this._CommService.popItemSelected.emit(item);
 this.reduceCount.emit(this.itemToPop);
 this.list.pop(this.itemToPop);
 }
 ngOnInit() {
 console.log("list",this.list);

} 发射组件HTML:

<div style="border: 2px; background-color:darkgray; width:300px;" >
 <ul>
 <li *ngFor="let item of list" [class.selected]="item === selectedItem"
 (click)="onSelect(item)">
 {{item}}<button class="button" (click)="popItem(item)">X</button>
 </li>
 </ul>
</div>

应用模块代码:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { ChildCommService } from './components/child-comm.service';
import { AppComponent } from './app.component';
import { DetailsComponent } from './components/details/details.component';
import { PopListComponent } from './components/pop-list/pop-list.component';
​
@NgModule({
 declarations: [
 AppComponent,
 DetailsComponent,
 PopListComponent
 ],
 imports: [
 BrowserModule,
 FormsModule
 ],
 providers: [ChildCommService],
 bootstrap: [AppComponent]
})
export class AppModule { }

请注意组件无法订阅的原因。是否有任何概念错误,因为编译器或控制台没有显示任何错误。

1 个答案:

答案 0 :(得分:0)

我有类似的问题。不知怎的,当我使用next时,发射不起作用,但它起了作用。在“details.component.ts”中,更改以下行:

this.reduceCount.emit(this.itemToPop);

this.reduceCount.next(this.itemToPop);