我以前通过以下方式完成此操作。就像 Budhead2004 所说,您绝对应该做一些研究,并找到适合您需求的良好状态管理解决方案。这个方法是我自己稍微滚动的,但它可以为较小的应用程序或代码部分完成工作。
这里是一个堆栈闪电战,展示了这一点:https://stackblitz.com/edit/angular-7gjfgt
store.service.ts 管理数据的状态并将MeasuringPoints 的数组映射到每个点的各个可观察对象。
store.service.ts
import { Injectable } from '@angular/core';
import { Subject, BehaviorSubject, Observable, from } from 'rxjs';
import { mergeMap, tap } from 'rxjs/operators'
import { MeasuringPoint } from './measuring-point';
const STUB_DATA: MeasuringPoint[] = [
{ data: 'fake data 1' },
{ data: 'fake data 2' },
{ data: 'fake data 3' },
];
@Injectable({ providedIn: 'root' })
export class StoreService {
// If you receive the data as an array, you will want to store it as an array
private _subject: Subject<MeasuringPoint[]> = new BehaviorSubject([]);
// Simple state management. Could switch this out for
// a caching library or NGRX
private loadedData: boolean = false;
constructor(/* inject needed services (ie. http, etc) */) { }
// Return single MeasuringPoint objects
public getAllMeasuringPoints$(): Observable<MeasuringPoint> {
// If you haven't loaded the data yet, load it now
if (!this.loadedData) {
this._subject.next(STUB_DATA);
this.loadedData = true;
}
return this._subject
// return the observable and not the subject
.asObservable()
// Convert the array of MeasuringPoints to emit for each
// value in the array
.pipe(
// Log values for demonstration
tap((values: MeasuringPoint[]) => console.log('Values before mapping: ', values)),
// convert an observable of an array to individual observables
mergeMap((points: MeasuringPoint[]) => from(points)),
// Log values for demonstration
tap((value: MeasuringPoint) => console.log('Values after mapping: ', value)),
);
}
}
然后您可以订阅公开的方法来获取您的数据。任何组件都可以订阅它。因为它是一个BehaviorSubject,所以订阅者总是会得到最近发出的值。关于BehaviorSubject 需要注意的另一件事是,由于 store.service 中的 observable 永远不会完成,因此您的组件在销毁时需要取消订阅。否则,您将在整个应用程序中出现内存泄漏。
first-component.component.ts -- 注意:second-component.component.ts 几乎是这个的副本
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subject } from 'rxjs';
import { StoreService } from './store.service';
import { takeUntil } from 'rxjs/operators';
import { MeasuringPoint } from './measuring-point';
@Component({
selector: 'app-first-component',
template: `
<h3>First Component</h3>
<div *ngFor="let point of measuringPoints">
{{point | json}}
</div>
`
})
export class FirstComponentComponent implements OnInit, OnDestroy {
public measuringPoints: MeasuringPoint[] = [];
// Keep track of subscriptions
private _endSubscriptions: Subject<null> = new Subject();
constructor(private _storeService: StoreService) { }
ngOnInit() {
this._storeService.getAllMeasuringPoints$()
// This is to avoid memory leaks by unsubscribing when your component destroys
.pipe(takeUntil(this._endSubscriptions))
.subscribe((point: MeasuringPoint) => this.measuringPoints.push(point));
}
ngOnDestroy() {
this._endSubscriptions.next();
this._endSubscriptions.complete();
}
}
这里是 RxJS 的文档from():https://www.learnrxjs.io/operators/creation/from.html
这应该会给您想要的结果。如果没有,请告诉我。干杯!