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?? } }
The main idea here is that if you want to update the value of an Observable you have to do this inside the 'create' function. This will be possible if you declare a function inside this 'create' function. For this implementation, you only need one Service.
An ObservableValue is an entity that wraps a value and allows to observe the value for changes. In general this interface should not be implemented directly but one of its sub-interfaces ( ObservableBooleanValue etc.). The value of the ObservableValue can be requested with getValue() .
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?
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