Add Data To The End Of A Behavior Object Array Angular 5


Answer :

You can add a new method to your service like addData in which you can combine your previous data with new data like.

import {Injectable} from '@angular/core'; import {BehaviorSubject} from 'rxjs/BehaviorSubject';  @Injectable()  export class UserService {     userDataSource: BehaviorSubject<Array<any>> = new BehaviorSubject([]);      userData = this.userDataSource.asObservable();      updateUserData(data) {         this.userDataSource.next(data);     }      addData(dataObj) {         const currentValue = this.userDataSource.value;         const updatedValue = [...currentValue, dataObj];         this.userDataSource.next(updatedValue);     } } 

For someone that may come accross this issue with a BehaviorSubject<YourObject[]>.

I found in this article a way to properly add the new array of YourObject

import { Observable, BehaviorSubject } from 'rxjs'; import { YourObject} from './location'; import { Injectable } from '@angular/core'; @Injectable({     providedIn: 'root' }) export class ObjService {     private theObjData: BehaviorSubject<YourObject[]> = new BehaviorSubject<YourObject[]>(null);      constructor() {     }      public SetObjData(newValue: YourObject[]): void {         this.theObjData.next(Object.assign([], newValue));     } }  

How to update data:

// inside some component this.api.userData().subscribe((results:YourObject) =>      this.objService.SetObjData(results); ) 

How to observe changes on other component

// inside another component ngOnInit() {     this.objService.GetAccountStatements().subscribe((results) =>     ...     ) } 

Comments

Popular posts from this blog

Are Regular VACUUM ANALYZE Still Recommended Under 9.1?

Can Feynman Diagrams Be Used To Represent Any Perturbation Theory?