Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Observable from a string (Angular 2)

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.

like image 559
be-codified Avatar asked Feb 22 '16 14:02

be-codified


1 Answers

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.

like image 162
Thierry Templier Avatar answered Oct 10 '22 15:10

Thierry Templier