如果 this.contacts
是一个对象列表的 Observable (contacts: Observable<Items[]>
) 并且您想对该列表进行一些更改,则可以简单地使用 tap
:
import { tap } from 'rxjs/operators';
this.contacts.pipe(tap(usersList => {
usersList.push(newItem);
}));
但是如果您想向服务器发出另一个请求并合并这些列表,您可以使用merge
:
import { merge } from 'rxjs';
merge(
this.contacts,
this.http.get('https://jsonplaceholder.typicode.com/other_users');
).pipe(
map(data => {
const [currentResult, pastResult] = data;
}
));
更新
根据您的评论所述,您不需要对可观察对象进行任何操作。您需要的是像这样的东西:
在您的contacts.service.ts
文件中:
getContacts(){
return this.http.get('https:
}
在你的contacts.component.ts文件中:
contacts: any[] = [];
ngOnInit() {
this.contactsService.getContacts().subscribe(data => {
this.contacts = data;
});
}
addContact(item) {
this.contacts.push(item);
}
但是,如果你想将你的联系人列表作为可观察对象,你应该使用一个Subject
。
在你的contacts.service.ts
文件中:
contactsChange$ = new Subject<any>();
private contactsList = [];
getContacts(){
return this.http.get('https://jsonplaceholder.typicode.com/users').pipe(tap(data => {
this.contactsList = data;
this.contactsChange$.next(this.contactsList);
}));
}
addContact(item) {
this.contactsList.push(item);
this.contactsChange$.next(this.contactsList);
}
在您的 contacts.component.ts 文件中:
contacts: any[] = [];
ngOnInit() {
this.contactsService.getContacts().subscribe(data => {this.contacts = data});
this.contactsService.contactsChange$.subscribe(data => {this.contacts = data});
}
subscribe()
方法订阅Observable时,才能获取联系人/用户数据。文档比我更好地解释了这一点(https://angular.io/guide/observables)。无论如何,你可能想要向你的联系人添加一个项目? - gillesB