Observable from a string (Angular 2)
Asked Answered
S

2

12

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.

Surber answered 22/2, 2016 at 14:54 Comment(2)
Waht about this.notice.unsubscribe() in ngDestroy() too? I know that's a common cause of memory leaks for manually added event listeners... So I presume this would be the same.Arizona
I'd also be considering BehaviorSubject too for this. #39494558Arizona
C
19

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.

Crossing answered 22/2, 2016 at 14:55 Comment(4)
thank you for showing this. I am wondering how to make 'some string' as a value of variable that could change. How to push it inside Observable then?Surber
In fact, you can't. That said you can fire event when the value changes. For this you need to create a raw observable: Observable.create((observer) => { observer.next('some string'); });. The next method can be called several times... Note that you can set the observer variable into a variable outside the callback.Crossing
You're welcome! I think the problem is at the level of your set method. I updated my answer...Crossing
I would create the observable without the word observable var obs = of('some string');Nonjoinder
E
2

I found out that we can create an Observable by using method "of" from the rxjs library. Because I had difficulties using the method "Observable.of" from the previous answer, I'm giving you my solution.

import {
  Observable,
  of,
} from 'rxjs';

  //message2: string = '...';  // old code
  message2$: Observable<any>;
  
  ngOnInit():void {
    this.message2$ = of('...');
  }

Full example on StackBlitz.

Evelinevelina answered 22/2, 2023 at 5:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.