訂閱組件 「彈出list.component.ts」:子組件無法通過該服務訂閱EventEmitter
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>
的服務「 ChildCommService.service.ts「:
import { Injectable, EventEmitter } from '@angular/core';
@Injectable()
export class ChildCommService {
popItemSelected = new EventEmitter<any>();
constructor() { }
}
的發射器組件 」details.component.ts「:
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 { }
請看到它,爲什麼組件無法認購。是否有任何概念錯誤,因爲編譯器或控制檯不顯示任何錯誤。
你不應該在你的服務中使用EventEmitter:https://stackoverflow.com/questions/36076700/what-is-the-proper-use-of-an-eventemitter。用主題替換它,當你這樣做時,你會問爲什麼數據未定義,這是因爲你在你的組件和模塊中多次提供它,這使得它重複https://stackoverflow.com/questions/43997489/角共享服務之間的組件-犯規工作。請閱讀官方文檔:https://angular.io/guide/component-interaction – echonax