简体   繁体   中英

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM