【问题标题】:Type 'number' is not assignable to type 'TeardownLogic'类型“编号”不可分配给类型“TeardownLogic”
【发布时间】:2020-02-16 20:47:31
【问题描述】:

我做了一个返回时间的服务Observable

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

但是,它给出了以下错误,

src/app/services/date.service.ts(11,5) 中的错误:错误 TS2322:类型“编号”不可分配给类型“TeardownLogic”。

我找到了这个解决方案(Typescript Error: setInterval - Type 'Timer' is not assignable to type 'number'),但无济于事。

【问题讨论】:

    标签: angular observable teardown


    【解决方案1】:

    据我了解,您在声明时间类型或其他内容时遇到了一些问题。看看下面的解决方案:

    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)
        })
      }
    }
    

    控制台输出

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

    【讨论】:

    • @Krishanu Noobserver.complete() 这行刚刚停止订阅。在我看到你的代码之前我不能说
    猜你喜欢
    • 1970-01-01
    • 2020-04-02
    • 2019-06-02
    • 2018-01-04
    • 2020-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多