属性'interval'在'typeof Observable'类型上不存在.ts(2339)

时间:2019-09-19 13:51:21

标签: javascript angular

我的目标:

  

我想创建一个计时器应用程序,提示用户输入   时间(以秒为单位),应用程序将倒计时到指定的时间   输入的时间(这是一个倒数计时器:您以秒为单位输入时间,   应用程序将从您输入的值倒计数到零)

import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { interval } from 'rxjs';
import 'rxjs/add/observable/interval';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/takeWhile';
import 'rxjs/add/operator/do';


const interval = Observable.interval(100);
           interval
            .takeWhile((_: any) => !this.isFinished )
            .do( () => this.current += 0.1)
            .subscribe();

版本详细信息:

  • Angular CLI:8.3.5
  • 节点:12.2.0
  • rxjs:6.4.0

编辑: 我想插入以下代码:

const interval = Observable.interval(100);
               interval
                .takeWhile((_: any) => !this.isFinished )
                .do( () => this.current += 0.1)
                .subscribe();

达到 rxjs:6.4.0 的最新标准,所有其他内容保持不变(试图弄些行话,但我仍然被Angular弄脏了手

2 个答案:

答案 0 :(得分:0)

Rxjs 6不想让您使用深层导入!您应该使用.pipe方法将操作链接在一起,这些操作又是从rxjs/operators导入的。

import { Component, OnInit } from '@angular/core';
import { interval } from 'rxjs';
import { map, takeWhile } from 'rxjs/operators';


const interval = interval(100);

let current = 0;
interval.pipe(
  takeWhile((_: any) => current < 5),
  map((_: any) => {current += 0.1; return current; })
).subscribe(
  (value: any) => {
    console.log(value);
    // Do something here while current < 5
  }
)

答案 1 :(得分:0)

使用rxjs 6+,您应该按照本update guide所述从'rxjs/operators'导入运算符,并从'rxjs'导入Observable函数,并且现在将pipe()与{ {3}}。

应该这样做:

import { interval } from 'rxjs';
import { takeWhile, map } from 'rxjs/operators';

const userValueSeconds = 3;

interval(100).pipe(    // run every 100ms
  takeWhile(i => userValueSeconds - (i/10) >= 0 ),  // stop when it gets to the value entered
  map(i => i * 100)                                  // map to ms
).subscribe(ms => console.log(ms));

here代码:

<input type="text" placeholder="Seconds" [formControl]="secondsCtrl">
<button (click)="run(secondsCtrl.value)">Run</button>
<div> TIMER: {{timer$ | async | date : 'mm:ss:SS'}} </div>
import { Component, OnInit } from '@angular/core';
import { Observable, interval } from 'rxjs';
import { takeWhile, map } from 'rxjs/operators';
import { FormControl } from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit  {

  secondsCtrl: FormControl;
  timer$: Observable<number>;

  ngOnInit(){
    this.secondsCtrl = new FormControl(3);
  }

  run(seconds: number) {
    this.timer$ = interval(100).pipe(
      takeWhile(i => seconds - (i/10)  >= 0 ),
      map(i => i * 100)
    );
  }


}