Angular 8 Observable.interval changed?
Asked Answered
M

4

6

I am trying to use Observable.interval on angular 8 and it doesn't seem to like it.

First I import rxjs:

import { Observable } from 'rxjs';

Then the code:

Observable.interval(1000).subscribe(x => {
    // something
  });

What is the angular 8 syntax?

Madancy answered 25/9, 2019 at 8:45 Comment(2)
import { interval } from 'rxjs'; and you use it directly.Underdeveloped
Note for the future: Be more precise than "it doesn't seem to like it" when asking questions. Look at the error you get and search for it on Google before. If you can't find anything, include it in the question on stackoverflowFredrick
C
19

Can you try something like this:

import { interval } from 'rxjs';

interval(1000).subscribe(x => {
// something
});
Cheek answered 25/9, 2019 at 8:47 Comment(3)
That doesn't seem to work either .. says identifier expectedMadancy
which version of rxjs do you use ?Cheek
Yeahh thanks.. it worked for me to call API in intervalsEcholalia
E
6

you can use interval like below. It works in angular12 also.

import { interval } from 'rxjs';

export class ObservableComponent implements OnInit, OnDestroy {
    intervalSubscription: Subscription;
    source = interval(1000);

    constructor() {}

    ngOnInit(): void {
        /*every 1second it emits value 0,1,2... 
        if we move to other component(destroy the component) it won't stop 
        incrementing and  another interval created along with the old 
        interval. Untill we unsubscribed it it 
        won't stop the incrementing process
        */
        this.intervalSubscription = this.source.subscribe(val => 
        console.log(val)); 
    }

    ngOnDestroy() {
        //when you move to another component, now the interval will be 
        //unsubscribed.
        this.intervalSubscription.unsubscribe();
    }    
}
Eulaheulalee answered 29/10, 2021 at 8:23 Comment(0)
F
3

*// Use RxJS v6+ and emit value in sequence every 1 second

import { interval } from 'rxjs';
const source = interval(1000);
const subscribe = source.subscribe(val => console.log(val));

//output: 0,1,2,3,4,5....

Fishbein answered 30/12, 2019 at 6:25 Comment(0)
C
3

Use timer if you want to wait n seconds before the first run or run it immediately and then every n seconds.

Wait 3 seconds and then run every second:

import { timer } from 'rxjs';

timer(3000, 1000).subscribe(x => {
// something
});

Run immediately and after that every 1 second (I don't know if this is the most elegant way to do it, but it's much simpler than other solutions I've seen, and it works):

import { timer } from 'rxjs';

timer(0, 1000).subscribe(x => {
// something
});
Chickabiddy answered 18/2, 2021 at 15:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.