简体   繁体   中英

Error: Property timer doesn't exist on type typeof Observable

The code is below

import {Component} from 'angular2/core';
import {Observable} from 'rxjs/Rx';

@Component({
selector: 'my-app',
template: 'Ticks (every second) : {{ticks}}'
})
export class AppComponent {
   ticks =0;

   click(){
      let timer = Observable.timer(2000,1000);
      timer.subscribe(t=>this.ticks = t);
   }
}

But i am getting an error. The error is in the following line:

let timer = Observable.timer(2000,1000);

The definition of error is "property timer doesn't exist on type typeof Observable" Why am I getting error like that? What do you think?

Thats because you havent patched the timer method into the Observable prototype.

Update: Rxjs 6.0.0

Import the creation method as a static pure function:

import { timer } from 'rxjs';
let timer$ = timer(2000,1000);

Original answer:

You have 2 options:

1) Patch the method with:

import 'rxjs/add/observable/timer';

2) Import the operator as a static pure function:

import { timer } from 'rxjs/observable/timer';
let timer$ = timer(2000,1000);

Personally I would recommend the 2nd approach.

The timer function now need to be imported directly from rxjs library, Below works fine.The message 'fired' will be seen in console after 10 seconds.

import { timer } from 'rxjs';

const numbers = timer(10000);
numbers.subscribe(any => console.log('fired'));

Please see this link for more details: https://rxjs-dev.firebaseapp.com/api/index/function/timer

您需要做的就是从库的根文件夹中导入Observable,因为旧版本的 rxjs 没有在 rxjs/Observable 中提供完整的 Observable 类

import {Observable} from 'rxjs';

If all you need is a timer, you could use this too:

setInterval(() => {
      this.callNecessaryMethod();
    }, this.intervalInMilliSeconds);

This is the function prototype:

function setInterval(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timer (+2 overloads)

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