Purpose: The goal is to append a new object to an existing Observable array of objects and ensure that this change is visible on the DOM as the final step.
NewObject.ts
:
export class NewObject {
name: string;
title: string;
}
Here's the example.component.ts
:
import { Observable } from 'rxjs';
import { Component, OnInit, Inject, EventEmitter } from '@angular/core';
import { NewObject } from 'objects';
@Component({
selector: 'app-example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.css']
})
export class ExampleComponent implements OnInit {
// Starting with an observable array of objects initialized from a service (step 1)
readonly objects$: Observable<NewObject[]> = this.objectSvc.getAllObjects("objects").pipe(
map(obj => obj.map(x => ({ name: x.name, title: alterString(x.title) }))),
shareReplay(1)
);
constructor(
private objectSvc: ObjectService
) { }
ngOnInit() {
funcToAdd = (response: any) => {
let data = JSON.parse(response);
data.forEach(x => {
let obj: NewObject = { name: x.name, title: alterString(x.title) }
// Trying to add the obj object into the existing object array Observable here
});
};
funcToDelete = (response: any) => {
let data = JSON.parse(response);
data.forEach(x => {
let obj: NewObject = { name: x.name, title: alterString(x.title) }
// Attempting to delete the obj object from the current object array Observable here
});
};
}
}
This is my example.component.html
:
<div *ngFor="let o of objects$ | async">
<p>{{ o.name }}</p>
<p>{{ o.title}}</p>
</div>
Here's my service object.service.ts
:
import { Injectable } from '@angular/core';
import { Observable, throwError, of } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
import { ClientApi, ApiException, NewObject } from '../client-api.service';
@Injectable({
providedIn: 'root'
})
export class ObjectService {
constructor(
private clientApi: ClientApi
) { }
getAllObjects(name: string): Observable<NewObject[]> {
return this.clientApi.getAllObjects(name)
.pipe(
map((x) => x.result),
catchError(err => {
if (ApiException.isApiException(err)) {
if (err.status === 404) {
return of<NewObject[]>(undefined);
}
}
return throwError(err);
})
);
}
}
Once the JSON response has been formatted, the objective is to insert the obj
object into the objects$
Observable and display it in the UI.
A suggestion has been made to utilize a BehaviorSubject
element. Any guidance on how this can be accomplished smoothly would be much appreciated.