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){
}
}
Subscribinglink An Observable instance begins publishing values only when someone subscribes to it. You subscribe by calling the subscribe() method of the instance, passing an observer object to receive the notifications. Returns an Observable instance that synchronously delivers the values provided as arguments.
RxJS (Reactive Extensions for JavaScript) is a library for reactive programming using observables that makes it easier to compose asynchronous or callback-based code.
Subscribe() is a method in Angular that connects the observer to observable events. Whenever any change is made in these observable, a code is executed and observes the results or changes using the subscribe method. Subscribe() is a method from the rxjs library, used internally by Angular.
here is a code example to get an array from an observable in Angular. We can use Observable. of method to convert an array to observable. Declare and initialized an array Pass this an array to the of method Here is a complete code in Angular. Sometimes, We want to find the length of an array to check an empty length.
That “thing” is called a producer and is a source of values, perhaps from the click or input event or something more complex such as communication over HTTP. In Angular, we generally use an Observable when we got the data from the server. So Async data is a perfect example of using Observables in Angular. What is an observer in RxJS?
The observable subscribe method is used by angular components to subscribe to messages that are sent to an observable. Subject.next() The subject next method is used to send messages to an observable which are then sent to all angular components that are subscribers (a.k.a. observers) of that observable.
The subject next method is used to send messages to an observable which are then sent to all angular components that are subscribers (a.k.a. observers) of that observable. Here's a simple example showing communication between the home component and the root app component via a message service using observables.
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;
// ...
}
));
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});
}
Working With Observable
In Your Service
private contactInsertedSubject = new Subject<Contact>();
contactInsertedActions$ = this.contactInsertedSubject.asObservable();
public contacts$ = this.http.get<Contact[]>(this.contactsUrl)
.pipe(
// tap(data => console.log('Contacts: ', JSON.stringify(data))),
catchError(this.handleError)
);
public contactsWithAdd$ = merge(this.contacts$, this.contactInsertedActions$)
.pipe(
scan((acc: Product[], value: Product) => [...acc, value])
);
addContact(newContact?: Contact) {
this.contactInsertedSubject.next(newContact);
}
Your Contact Component Class
contacts$ = this.contactService.contactsWithAdd$;
onAdd(): void {
this.contactService.addProduct();
}
when this add method will call the subject in service will emit the value and merge observable has two input observable if any one will emit value so this will call automatically and then in pipe map operator will do the insertion job and contactWithAdd observable will have updated list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With