angularobservableteardown

Type 'number' is not assignable to type 'TeardownLogic'


I made a service that returns a time Observable,

time = new Observable(observer =>
    setInterval(() => observer.next(new Date().toString()), 1000)
);

However, it gives the following error,

ERROR in src/app/services/date.service.ts(11,5): error TS2322: Type 'number' is not assignable to type 'TeardownLogic'.

I found this solution(Typescript Error: setInterval - Type 'Timer' is not assignable to type 'number') but to no avail.


Solution

  • As far as I understand you have some issue while declaring type of time or something else. Have a look to below solution:

    export class AppComponent {
      time: Observable<string>;
      constructor() {
        this.time= new Observable(observer => {
          setInterval(() => {
            observer.next(new Date().toString());
            observer.complete();
          }, 1000);
        });
        this.time.subscribe(value => {
          console.log(value)
        })
      }
    }
    

    Output in console

    Mon Nov 18 2019 21:18:50 GMT+0530 (India Standard Time)