猿问

如何使用角度的可观察值返回数字/变量?

我有一个角度服务调用 API 并返回大量数据。在同一个 GET 调用中,我正在做一些逻辑来计算每种类型的数量。我的问题很简单,我可以将那个变量/数字和数据一起发回,或者甚至将它保存到另一个变量并发送它吗?


当我尝试将它作为公共变量保存到服务中时,当我尝试将它拉入另一个组件时它是未定义的。我假设是因为在订阅 observable 之前访问了变量,但我不知道如何解决这个问题?


在下面的代码中,_counts 是我要返回的内容,它可以在 getPciInfo 方法中很好地进行日志记录,但就像我说的那样,它在其他任何地方都以未定义的形式返回。(我正在尝试将此数字传递给不同的组件)。


感谢您提供的任何帮助或建议。


public _counts: any;


getPciInfo(): Observable <Ipcidata[]> {

    return this.httpClient.get<Ipcidata[]>('http://dr0-hlp-07/api/PCIMachines')

      .pipe(

              map(results => {


                const sorted = results.sort(( a, b ) => {

                      const updateDateA = Date.parse(this.datepipe.transform(a.UpdatedDate, 'MM-dd-yyyy'));

                      const carda = determineCardType(a, this.dateMinusMonth, this.dateMinusTwoWeeks)

                      const cardb = determineCardType(b, this.dateMinusMonth, this.dateMinusTwoWeeks)


                      return cardb - carda

                });


                this._counts = sorted.reduce((acc, cur)=>{

                  const cardType = determineCardType(cur, this.dateMinusMonth, this.dateMinusTwoWeeks)


                  switch (cardType) {

                    case 1:

                      acc.green += 1;

                      break;

                    case 2:

                      acc.yellow += 1;

                      break;

                    case 3:

                      acc.red += 1;

                      break;

                  }

                  return acc;

                }, {

                  red: 0,

                  green: 0,

                  yellow: 0

                });

                console.log(this._counts)

                console.log(this._counts.red)


          return sorted;

          }


慕的地8271018
浏览 144回答 1
1回答

阿波罗的战车

要发回计数,您可以执行以下操作:return ({sorted, counts: _counts});要在此服务的组件之间共享它,您可以拥有一个主题,例如:private countsSource = new Subject();private counts = this.countsSource.asObservable();getPciInfo(): Observable <Ipcidata[]> {&nbsp; &nbsp; return this.httpClient.get<Ipcidata[]>('http://dr0-hlp-07/api/PCIMachines')&nbsp; &nbsp; &nbsp; .pipe(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; map(results => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;....&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;const counts = ...&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;this.countsSource.next(counts)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; });}getCounts(): Observable<CountData> {&nbsp; &nbsp; &nbsp;return this.counts;}在一个组件中,你可以像其他函数一样使用它this.myService.getCounts().subscribe(counts => console.log(counts));如果您希望将计数发送到新订阅,您可能必须使用BehaviorSubject或ReplaySubject。
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答