0

I am new to Observer in Angular4 as I have worked on Promises in AngularJs. I want to understand 2 scenarios:

  1. Returning observable from a function so that the UI can be changed accordingly.

  2. Returning continuous stream of data from a function which is reflected on the UI.

In a service (proc.svc.ts) file I created a function:

counter(){
   public counterObserver = Observable.create(obs => {
    obs.next(increment())
   });
  return counterObserver;
 }

increment(){
  setInterval(function(){
  count++
 },1000)
}

In the proc.component.ts file:

ngOnInit() {
   this.initCounter();
 }

initCounter(){
  this.procSvc.counter.subscribe(count => this.count = count);
}

I am getting below error:

Property 'subscribe' does not exist on type '() => void'.

1
  • 1
    You created a function : call counter(), not counter ! Commented Dec 21, 2017 at 8:04

1 Answer 1

1

seem like problem with the code also , if you want to push value at specific interval than you have to push vlaue on ovserver , like as given below push value from setInterval() function , that is also problem with you code

const evenNumbers = Rx.Observable.create(function(observer) {
  let value = 0;
  const interval = setInterval(() => {
    if (value % 2 === 0) {
      observer.next(value);
    }
    value++;
  }, 1000);

  return () => clearInterval(interval);
});
//output: 0...2...4...6...8
const subscribe = evenNumbers.subscribe(val => console.log(val));

one more thing as in example its directly subscribing to oberserver not function there is no () present but in you case its fuction as i pointed out below


try like this , as counter is function and that is problem with you code seems like

initCounter(){
  this.procSvc.counter().subscribe(count => this.count = count);
}

you have to provide return type here

counter(): Observable<datatype>{

right now it seems empty that means void. or i do as below when datatype is not known

 public getData(path: string):Observable<any>{
    return this.http.get(path, options)
        .map((response: Response) => response.json())  ;
  }

then aply subscribe on that

 getData("val").subscribe();

also import

import { Observable } from 'rxjs/Observable';
Sign up to request clarification or add additional context in comments.

2 Comments

@Samuel - that is to dispose timer..means when you unsubscribe observer than this function clear the timer that you creaed..check example here : learnrxjs.io/operators/creation/create.html
@Samuel - you can see here : github.com/ReactiveX/rxjs/issues/76

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.