Angular 6将项目添加到Observable [英] Angular 6 add items into Observable
问题描述
我是Angular 6的新手,我在如何将对象添加到服务中的可观察对象时遇到麻烦.
I'm new to Angular 6 and i'm having trouble on how i can add objects into observable in a service.
我有这个可观察的
getContacts(){
return this.contact =
this.http.get('https://jsonplaceholder.typicode.com/users');
}
我需要通过另一个函数在该可观察项中添加一个项
and i need to add an item into that observable via another function
addContact(item){
//observable insertion goes here.
}
这是我的完整服务代码
export class ContactService {
contact;
details;
constructor(private http: HttpClient) {}
getContacts(){
return this.contact =
this.http.get('https://jsonplaceholder.typicode.com/users');
}
addContact(contactName: string, contactPhone: string){
}
}
推荐答案
如果this.contacts
是对象列表(contacts: Observable<Items[]>
)的可观察对象,并且您想要对该列表进行一些更改,则可以简单地使用
If this.contacts
is an Observable of list of objects (contacts: Observable<Items[]>
) and you want to make some changes to that list, you can simply use map
:
import { map } from 'rxjs/operators';
this.contacts.pipe(map(usersList => {
usersList.push(newItem);
return usersList;
}));
但是,如果要向服务器发出另一个请求并合并这些列表,则可以使用forkJoin
:
But if you want to make another request to the server and merge these lists, you can use forkJoin
:
import { forkJoin } from 'rxjs';
forkJoin(
this.contacts,
this.http.get('https://jsonplaceholder.typicode.com/other_users');
).pipe(
map(data => {
const [currentResult, pastResult] = data;
// ...
}
));
更新
根据您的评论以获取更多详细信息,您无需对可观察对象做任何事情.您需要的是这样的:
Update
Based on your comment for more details, you don't need to do anything with observables. What you need is something like this:
在您的contacts.service.ts
中:
getContacts(){
return this.http.get('https://jsonplaceholder.typicode.com/users');
}
在您的contacts.component.ts中:
In your contacts.component.ts`:
contacts: any[] = [];
ngOnInit() {
this.contactsService.getContacts().subscribe(data => {
this.contacts = data;
});
}
addContact(item) {
this.contacts.push(item);
}
但是,如果您确实希望将联系人列表作为可观察对象",则应使用Subject
.
But if you really want to have your contacts list as an Observable, you should use Subject
.
在您的contacts.service.ts
中:
$contactsChange = new Subject<any>();
private contactsList = [];
getContacts(){
return this.http.get('https://jsonplaceholder.typicode.com/users').pipe(map(data => {
this.contactsList = data;
this.$contactsChange.next(this.contactsList);
}));
}
addContact(item) {
this.contactsList.push(item);
this.$contactsChange.next(this.contactsList);
}
在您的contacts.component.ts中:
In your contacts.component.ts`:
contacts: any[] = [];
ngOnInit() {
this.contactsService.getContacts().subscribe(data => {this.contacts = data});
this.contactsService.$contactsChange.subscribe(data => {this.contacts = data});
}
这篇关于Angular 6将项目添加到Observable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!