Typescript Angular - Observable: how to change its value?

Johannes picture Johannes · Feb 28, 2017 · Viewed 87.3k times · Source

Maybe I'm missing something. I can't find a simple tutorial for Observable and its syntax. I'm working with Angular, I need to call a function (defined in a component) from a service. I read this solution. But I can't figure out how to change the value in the Observable created in the service (maybe the creation is not the best method).

I have a component like in the solution:

@Component({
  selector: 'my-component',
  ...
)}
export class MyComponent {
   constructor(myService:MyService) {
   myService.condition.subscribe(value => doSomething(value));
}

doSomething(value) {
  if (value) // do stuff
  else // other stuff
}

}

and this is my service:

import { Injectable } from '@angular/core';
import { Observable} from 'rxjs/Observable';

@Injectable()

export class MyService {
    private condition: Observable<boolean>;
    constructor() { 
       this.condition= new Observable(ob => {ob.next(false); })
       // maybe ob.next is not the best solution to assign the value?
    }

    change() {// how can i change the value of condition to 'true', to call
              // the doSomething function in the component?? 
    }

}

Answer

msanford picture msanford · Feb 28, 2017

From the comments on my other answer (preserved since it may be helpful to someone), you seem to want to leverage the power of something to emit values over time.

As DOMZE proposed, use a Subject, but here's a (trivial) example showing how you could do that. Though there are evidently some pitfalls to avoid in using Subject directly, I'll leave that up to you.

import { Component, NgModule } from '@angular/core'
import { BrowserModule } from '@angular/platform-browser'
import { Observable, Subject } from 'rxjs/Rx';

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Open the console.</h2>
    </div>
  `,
})
export class App {

  constructor() {}

  let subject = new Subject();

  // Subscribe in Component
  subject.subscribe(next => {
    console.log(next);
  });

  setInterval(() => {
    // Make your auth call and export this from Service
    subject.next(new Date())
  }, 1000)
}

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule {}

Plunker

In my humble opinion, for this scenario, I don't see why a simple Service/Observable doesn't suffice, but that's none of my business.

Further reading: Angular 2 - Behavior Subject vs Observable?