Fra*_*bia 5 observable typescript angular
我是Angular 6的新手,我在如何将对象添加到服务中的可观察对象时遇到了麻烦。
我有这个可观察的
getContacts(){
return this.contact =
this.http.get('https://jsonplaceholder.typicode.com/users');
}
Run Code Online (Sandbox Code Playgroud)
我需要通过另一个功能向该可观察项添加一个项
addContact(item){
//observable insertion goes here.
}
Run Code Online (Sandbox Code Playgroud)
这是我的完整服务代码
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){
}
}
Run Code Online (Sandbox Code Playgroud)
如果this.contacts是对象列表(contacts: Observable<Items[]>)的Observable,并且您想要对该列表进行一些更改,则可以简单地使用map:
import { map } from 'rxjs/operators';
this.contacts.pipe(map(usersList => {
usersList.push(newItem);
return usersList;
}));
Run Code Online (Sandbox Code Playgroud)
但是,如果要向服务器发出另一个请求并合并这些列表,则可以使用forkJoin:
import { forkJoin } from 'rxjs';
forkJoin(
this.contacts,
this.http.get('https://jsonplaceholder.typicode.com/other_users');
).pipe(
map(data => {
const [currentResult, pastResult] = data;
// ...
}
));
Run Code Online (Sandbox Code Playgroud)
根据您的评论以获取更多详细信息,您无需对可观察对象做任何事情。您需要的是这样的:
在您的contacts.service.ts:
getContacts(){
return this.http.get('https://jsonplaceholder.typicode.com/users');
}
Run Code Online (Sandbox Code Playgroud)
在您的contact.component.ts`中:
contacts: any[] = [];
ngOnInit() {
this.contactsService.getContacts().subscribe(data => {
this.contacts = data;
});
}
addContact(item) {
this.contacts.push(item);
}
Run Code Online (Sandbox Code Playgroud)
但是,如果您确实希望将联系人列表作为可观察对象,则应使用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);
}
Run Code Online (Sandbox Code Playgroud)
在您的contact.component.ts`中:
contacts: any[] = [];
ngOnInit() {
this.contactsService.getContacts().subscribe(data => {this.contacts = data});
this.contactsService.$contactsChange.subscribe(data => {this.contacts = data});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9911 次 |
| 最近记录: |