如何监听 Angular 组件中的 Service 变量变化

时间:2021-04-05 21:19:01

标签: javascript angular typescript observable synchronous

我有一个带有按钮的组件,单击该按钮会触发 showSummary(),该按钮调用具有方法 Appraisal-summary.service.ts 的服务 calc()

showSummary(appraisal) {
  this.summaryService.calc(appraisal);
}

服务Appraisal-summary.service.ts

calc(appraisal) {
  ...
  //a 'scores' array is created (synchronously)
  return this.scores;
}

如何侦听同步结果 this.scores 以触发将使用 summary.component.ts 的无关组件 scores(已初始化)中的函数。

类似: summary.component.ts

ngOnInit(): void {
  service.subscribe(scores => this.data = scores)
}

1 个答案:

答案 0 :(得分:0)

您可能希望在您的 Subject 中添加一个 Appraisal-summary.service.ts,如下所示:

import { Subject } from 'rxjs';

...
export class AppraisalSummaryService {
    // I am guessing scores is an array of type number
    public scoreSubject = new Subject<number[]>(); 
    
    calc(appraisal) {
      ...
      //a 'scores' array is created (synchronously)
      
      this.scoreSubject.next(this.scores); //emit the scores result
      return this.scores;
   }
}

并且,在您的其他组件中,在您的 ngOnInit 中,您想要收听以下结果:

import { Subscription } from 'rxjs';
....
export class YourOtherComponent implements OnInit, OnDestroy {
   private subscription: Subscription;

   constructor(private appraisalSummaryService: AppraisalSummaryService) {}

   public ngOnInit(): void {
     // you store your subscribe
     this.subscription = this.appraisalSummaryService.subscribe((scores: number[]) => {
       console.log(scores);
    });
   }
   
   public onDestroy(): void {
     // you need this in order to avoid a memory leak
     this.subscription.unsubscribe();
   }
   
}
```