Hi I'm new on angular.
I don't know why I can't set new value in my Observable
My code :
resultJob: Observable<any> = Observable.of("PENDING");
ngOnInit() {
this.resultJob.subscribe(result => {
result.next("SUCCESS")
result.complete()
})
}
This code return result.next is not a function
In an Observable Execution, zero to infinite Next notifications may be delivered. If either an Error or Complete notification is delivered, then nothing else can be delivered afterwards.
Observables provide support for passing messages between parts of your application. They are used frequently in Angular and are a technique for event handling, asynchronous programming, and handling multiple values.
What is an Observer? An Observer is a consumer of values delivered by an Observable. Observers are simply a set of callbacks, one for each type of notification delivered by the Observable: next , error , and complete . The following is an example of a typical Observer object: const observer = { next: x => console.
The observer's complete() callback specifies the action to take when the observable has completed producing and emitting data. const observer = { complete: () => console. log('You have used up all the vowels.') }; JavaScript.
There is no next() on Observable; only on Subject and BehaviorSubject, which extends Subject (and both extend Observable).
What you need to do is:
resultJob: Subject<string> = new BehaviorSubject<string>("PENDING");
BehaviorSubject in contrast to Subject gets initialized with a first value that gets pushed in the stream. It seems to be what you want to do.
Also result is of type string, not of type Observable. You want to call next() on resultJob, not on result (the element inside the stream). But I don't understand why you do that in the Subscribtion. You will get circular calls this way: you push a new element in the stream and react on its detection by pushing another one and so forth...
here is sample example of observer. for more information about component interaction you can refer this doc Component interaction
Step 1:- app.module.ts
import { UserService } from './user.service';
@NgModule({
providers: [
UserService
]
})
Step 2:- user.service.ts
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';
@Injectable()
export class UserService {
users: any = null;
nativeWindow: any;
private userAddedSource = new Subject<any>();
userAdded$ = this.userAddedSource.asObservable();
addNewUser(user) {
this.userAddedSource.next({ user: user });
}
}
Step 3:- add this code in your component for sending data
this.userService.addNewUser({name:'xyz'}); // your data
Step 4:- On your receiver component
ngOnInit() {
this.userService.userAdded$.subscribe(data => {
console.log(data.user);
});
}
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