I am pretty new to Observables. How would I create Observable just from a simple string? Then subscribe to it and output it when it changes.
Does that make sense?
I don't have any luck with google search. Probably wrong keywords?
Adding some code for better explanation:
My constructor on service
constructor() {
// Create observable stream to output our data
this.notice = Observable.create(
(observer) => this.observer = observer;
);
};
My method on service
set(string) {
this.notice.subscribe((value) => {
// Push the new value into the observable stream
this.observer.next(string);
}, (error) => console.log('Could not set data.'));
}
Calling service method
setNotice(event) {
event.preventDefault();
// Calling service to set notice
this.noticeService.set('This is a string');
}
I think I am doing something wrong here? But not sure how to ask. I would be grateful for any of the explanations.
You can use the of
method of the Observable
class:
var obs = Observable.of('some string');
Edit
Regarding the code of your service, I would refactor the code of your set
method like this:
set(string) {
this.observer.next(string);
}
You can subscribe on the notice
property in another part of your application to be notified.
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