Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

typescript - Angular 6 add items into Observable

I'm new to Angular 6 and i'm having trouble on how i can add objects into observable in a service.

i have this observable

 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.
}

Here is my full service code

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){

}

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 tap:

import { tap } from 'rxjs/operators';

this.contacts.pipe(tap(usersList => {
  usersList.push(newItem);
}));

But if you want to make another request to the server and merge these lists, you can use merge:

import { merge } from 'rxjs';

merge(
  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:

In your contacts.service.ts:

getContacts(){
  return this.http.get('https://jsonplaceholder.typicode.com/users');
}

In your contacts.component.ts`:

contacts: any[] = [];
ngOnInit() {
  this.contactsService.getContacts().subscribe(data => {
    this.contacts = data;
  });
}

addContact(item) {
  this.contacts.push(item);
}

But if you want to have your contacts list as an Observable, you should use a Subject.

In your 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);
}

In your contacts.component.ts`:

contacts: any[] = [];
ngOnInit() {
  this.contactsService.getContacts().subscribe(data => {this.contacts = data});
  this.contactsService.contactsChange$.subscribe(data => {this.contacts = data});
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...