我真的無法爲「無關」Angular 2組件創建服務。然而,親子關係(我使用綁定或事件發射器)沒有問題。如何爲非親子Angular 2組件創建服務
我有3個文件:
- StatsService應攜帶數據。
- MatchBoard組件生成足球鏡頭
- StatsComponent將打印數量打印到屏幕上。
但我已經處理了幾個小時,閱讀了官方的A2文檔,仍然無法找出解決方案。
我想要什麼:我只是想生成鏡頭(每2秒),抓住他們的服務併發送到StatsComponent,以便它顯示屏幕上的鏡頭數量。那很簡單。
的StatsService部件
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';
@Injectable()
export class StatsService {
private homeTeamShots = new Subject<any>();
homeTeamShots$ = this.homeTeamShots.asObservable();
publishData(data:any){
this.homeTeamShots.next(data);
}
}
護牆板部件
import { Component, Input, OnInit, OnChanges } from '@angular/core';
import {StatsService} from '../stats.component/stats.service';
@Component({
selector: 'match-board',
templateUrl: './matchboard.component.html',
styleUrls: ['./matchboard.component.css']
})
export class MatchBoard implements OnChanges {
homeTeamShots:number = 0;
constructor(private _statsService:StatsService) {
this._statsService.homeTeamShots$.subscribe(
data => {
console.log('matchboard received this: ' + data);
}
)
}
ngOnChanges(){
}
onHomeTeamShot(){
this.homeTeamShots += 1;
this._statsService.publishData(this.homeTeamShots);
}
ngOnInit(){
// shots are taken every 2 seconds as a example
setInterval(()=> this.onHomeTeamShot(), 2000);
}
}
而且StatsComponent
import { Component, Input, OnInit, OnChanges } from '@angular/core';
import {StatsService} from '../stats.component/stats.service';
@Component({
selector: 'stats',
templateUrl: './stats.component.html',
styleUrls: ['./stats.component.css'],
providers: [StatsService]
})
export class StatsComponent implements OnChanges {
homeTeamShots:number;
constructor(private _statsService:StatsService) {
this.homeTeamShots = 0;
this._statsService.homeTeamShots$.subscribe(
data => {
this.homeTeamShots = data;
console.log('Sibling2Component-received from sibling1: ' + data);
}
);
}
ngOnChanges(){
}
onHomeTeamShot() {
this.homeTeamShots += 1;
console.log('number of shots in stats now ' + this.homeTeamShots);
this._statsService.publishData(this.homeTeamShots);
}
ngOnInit(){
setInterval(()=> console.log(this.homeTeamShots), 2050);
}
}
在控制檯中,我得到「企口收到此:2(然後是3,然後4像正常一樣)' from MatchBoard com Ponent(波納恩特)。 但是,這個問題始於StatsComponent - 它在'subscribe'之後被卡住,並且一直記錄爲'0'。
我試着在statsComponent的某個地方調用onHomeTeamShot(),但它從頭開始一直顯示'1'並且不會改變。
Omg,我甚至沒有注意到......浪費了12個小時...... :)非常感謝你!它現在有效。 –