Angular 角度订阅方法正在多次调用

Angular 角度订阅方法正在多次调用,angular,typescript,Angular,Typescript,在Angular 6上,我创建了一个服务 @Injectable({ providedIn: 'root' }) export class CrossEventService { public refresh$: EventEmitter<string> = new EventEmitter<string>(); public refreshSections(event: any) { this.refresh$.emit(event) } } 现在

在Angular 6上,我创建了一个服务

@Injectable({ providedIn: 'root' })
export class CrossEventService {
  public refresh$: EventEmitter<string> = new EventEmitter<string>();
  public refreshSections(event: any) {
    this.refresh$.emit(event)
  }
}
现在我正在检查Ngonit方法的另一个组件

 ngOnInit() {
    this.CrossEventService.refresh$.subscribe(data => {
      if (data) {
        // call whatever method i need to call from my current component
      }
    });
但是在某些地方,上面的subscribe方法正在多次调用?

在服务中避免EventEmitter: 我不确定您的目标是什么,但在服务中使用事件发射器是一种不鼓励的做法。在下面的文档中,我们应该使用对服务没有影响的@Output decorator(它用于子组件到父组件的通信)。在另一边,它迫使你暴露你的发射器

@Injectable()
export class MyService {
   @Output()   // <<< has no effect
   public events: EventEmitter<any> = new EventEmitter();
   // ^^ makes the emitter public
}
如果您想知道为什么要创建一个以_refreshSource$为源的refreshStream$,这是因为当我们想要公开来自主题的数据时,它很有用,但同时可以防止将新数据推回到主题中

因此,这就是为什么您需要触发RefreshSection,就像您在组件中所做的那样:

this.CrossEventService.refreshSections(""); 
然后订阅
refreshStream$
。请记住,订阅refreshStream的所有组件都将被激活并以主题的新值传递:

import {Subscription} from 'rxjs/Subscription';

export class ObservingComponent {
  subscription: Subscription;
  event: any;
  constructor(private _crossEventService:CrossEventService) {}
  ngOnInit() {
    this.subscription = this._crossEventService.refreshStream$
       .subscribe(event => this.event = event)
  }
  ngOnDestroy() {
    // prevent memory leak when component is destroyed
    this.subscription.unsubscribe();
  }
}

注意,我添加了一个来自RxJs的订阅,以便在组件被销毁时取消订阅主题。您还可以清楚地知道要将哪些信息传递给
。下一步({information})
,因为您可能可以跳过从
EventEmitter

继承的
事件
语法,它到底在哪里被多次调用?您可以在plunker中复制吗?如果您通过属性绑定或插值在模板中使用
this.CrossEventService.refreshSections(“”
),并且如果您使用默认的更改检测策略,则可以为每个CD周期触发它。然后将向订阅发出通知。
this.CrossEventService.refreshSections(""); 
import {Subscription} from 'rxjs/Subscription';

export class ObservingComponent {
  subscription: Subscription;
  event: any;
  constructor(private _crossEventService:CrossEventService) {}
  ngOnInit() {
    this.subscription = this._crossEventService.refreshStream$
       .subscribe(event => this.event = event)
  }
  ngOnDestroy() {
    // prevent memory leak when component is destroyed
    this.subscription.unsubscribe();
  }
}