【发布时间】:2020-05-23 06:32:45
【问题描述】:
目标:将对象添加到现有的 Observable 对象数组中。最后一步是在 DOM 上进行反射。
NewObject.ts:
export class NewObject {
name: string;
title: string;
}
这是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 {
// Initializing the object array Observable 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() {
somethingThatHappensToAdd = (response: any) => {
let data = JSON.parse(response);
data.forEach(x => {
let obj: NewObject = { name: x.name, title: alterString(x.title) }
// Here's where I'm trying to add the obj object into the already existing object array Observable
});
};
somethingThatHappensToDelete = (response: any) => {
let data = JSON.parse(response);
data.forEach(x => {
let obj: NewObject = { name: x.name, title: alterString(x.title) }
// Here's where I'm trying to delete the obj object from the already existing object array Observable
});
};
}
}
这是我的example.component.html:
<div *ngFor="let o of objects$ | async">
<p>{{ o.name }}</p>
<p>{{ o.title}}</p>
</div>
这是我的服务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);
})
);
}
}
在JSON 中格式化响应后,我希望能够将obj 对象插入objects$ Observable 并让它反映在用户界面上。
建议我使用BehaviorSubject 元素来实现这一点。任何人都可以建议如何轻松做到这一点?
【问题讨论】:
标签: angular typescript rxjs observable behaviorsubject