将数据添加到 ReplaySubject<ImpiantoModel[]> 但不被 next() 覆盖

add data to ReplaySubject<ImpiantoModel[]> but not overwrite with next()

我是 angular 的新手,我遇到了问题。 我正在使用 ReplaySubject 在组件之间共享数据,我得到了它,但我该如何更新我的数据?

我想每分钟从 http het 添加一个值,但是使用 Next() 方法我会覆盖所有数据。

这是我的文件:

数据-service.service.ts </p> <pre><code>import {Injectable, OnInit} from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { ReplaySubject } from 'rxjs/ReplaySubject'; import { Observable } from 'rxjs/Observable'; import {ImpiantoModel} from './impianto.model'; @Injectable() export class DataServiceService implements OnInit { private myUrl = ('https://my-json.server.typicode.com/nicscap/fake_json/ImpiantiProva'); myData: ReplaySubject<ImpiantoModel[]> = new ReplaySubject(); constructor(private http: HttpClient) { } stream$(): Observable<ImpiantoModel[]> { return this.myData.asObservable(); } ngOnInit() { this.http.get<ImpiantoModel[]>(this.myUrl) .subscribe( data => { this.myData.next(data); }); return this.myData; } private newdata = [ { 'nomeImpianto': 'MFL8', 'descrImpianto': 'Multifilo 8', 'posizione': 'Place8', 'dati_status': 'Place8', 'unita_misura': 'm/s' }, ]; pushData() { this.myData.next(this.newdata); } }

所以 data-service.service.ts 我发出了 http 请求,我希望 pushData() 附加 newdata 但它会被覆盖。

app.component.ts </p> <pre><code>import {Component, OnInit} from '@angular/core'; import {DataServiceService} from './data-service.service'; import {ImpiantoModel} from './impianto.model'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { title = 'app'; systems: ImpiantoModel[]; constructor(private _dataService: DataServiceService) {} getdata() { this._dataService.stream$().subscribe( result => this.systems = result ); } ngOnInit() { this._dataService.ngOnInit(); this.getdata(); } }

我希望通过推送“pushdata”将新数据插入到之前的数据之后,而不是覆盖它们。我能怎么做? 谢谢!!

如果http响应是一个数组,你只需要连接结果。

  this._dataService.stream$().subscribe((result) => {
      this.systems = this.systems.concat(result) // here
  });

您可以使用 scan 运算符随时间累积值

myData: ReplaySubject<ImpiantoModel> = new ReplaySubject();
stream$: Observable<ImpiantoModel[]>;

constructor(){
    this.stream$ = this.myData
        .asObservable
        // append current value on previous array
        .scan((acc, curr) => [...acc, curr], []);
}

这是一个 stackblitz 演示。