如何为非亲子Angular 2组件创建服务

如何为非亲子Angular 2组件创建服务

问题描述:

我真的无法为“无关”Angular 2组件创建服务。然而,亲子关系(我使用绑定或事件发射器)没有问题。如何为非亲子Angular 2组件创建服务

我有3个文件:

  1. StatsService应携带数据。
  2. MatchBoard组件生成足球镜头
  3. 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'并且不会改变。

原因是在StatsComponent线

providers: [StatsService] 

。这意味着StatsComponent有一个自己的服务实例。 解决方案是让组件中的提供者仅位于三个组件之上,并从StatsComponent中移除该行。

您可以找到有关,这里的一些详细信息:https://angular.io/guide/hierarchical-dependency-injection

+0

Omg,我甚至没有注意到......浪费了12个小时...... :)非常感谢你!它现在有效。 –

移所有的逻辑服务,并充分利用的Observables力量做繁重。

在您的服务中,使用.interval()创建一个Observable。这会照顾你的投票。您甚至不需要publishData(),因为您已经在使用Subject。我创建了一个名为generateShots()

import {Injectable} from '@angular/core'; 
import {Subject} from 'rxjs/Subject'; 

@Injectable() 
export class StatsService { 
    private homeTeamShots = new Subject<any>(); 
    homeTeamShots$ = this.homeTeamShots.asObservable(); 

    generateShots() { 
     return Observable.interval(2000) 
      .map(ticks => this.homeTeamShots$.next(ticks)); 
      //.interval() returns a single integer, starting from 0,1,2.... 
      //just simply update your subject with that value. 
    } 

} 

现在,在MatchBoard组件“开始”倒计时功能,只需订阅generateShots()

ngOnInit() { 
    this._statsService.generateShots() 
     .subscribe(shots => this.homeTeamShots = shots); 
    //this.homeTeamShots will increment from 0 to 1,2,3.... every 2000ms 
} 

而且在StatsComponent显示你的投篮,订阅您homeTeamShots$Subject

ngOnInit() { 
    this._statsService.homeTeamShots$.subscribe(
     data => { 
      this.homeTeamShots = data; 
      console.log('Sibling2Component-received from sibling1: ' + data); 
     } 
    ); 
} 

而瞧,你有两个组件通过单个共享服务(单例)同步数据。清洁。

+0

谢谢你,我是新来的反应的东西和Angular,但我会尽力通过做:)我会真的重做应用程序来处理事情通过服务 –