Update
If you want to call a function declared on the AppComponent class, you can do one of the following:
** Assuming the function you want to call is named func,
ngOnInit(){
let timer = Observable.timer(2000,1000);
timer.subscribe(this.func);
}
The problem with the above approach is that if you call 'this' inside func, it will refer to the subscriber object instead of the AppComponent object which is probably not what you want.
However, in the below approach, you create a lambda expression and call the function func inside it. This way, the call to func is still inside the scope of AppComponent. This is the best way to do it in my opinion.
ngOnInit(){
let timer = Observable.timer(2000,1000);
timer.subscribe(t=> {
this.func(t);
});
}
I faced a problem that I had to use a timer, but I had to display them in 2 component same time, same screen. I created the timerObservable in a service. I subscribed to the timer in both component, and what happened? It won't be synched, cause new subscription always creates its own stream.
What I would like to say, is that if you plan to use one timer at several places, always put .publishReplay(1).refCount()
at the end of the Observer, cause it will publish the same stream out of it every time.
If you look to run a method on ngOnInit you could do something like this:
import this 2 libraries from RXJS:
import {Observable} from 'rxjs/Rx';
import {Subscription} from "rxjs";
Then declare timer and private subscription, example:
timer= Observable.timer(1000,1000); // 1 second for 2 seconds (2000,1000) etc
private subscription: Subscription;
Last but not least run method when timer stops
ngOnInit() {
this.subscription = this.timer.subscribe(ticks=> {
this.populatecombobox(); //example calling a method that populates a combobox
this.subscription.unsubscribe(); //you need to unsubscribe or it will run infinite times
});
}
on the newest version of Angular (I work on 12.2.*) Observable.timer is not supported. You can use it with a bit change at @Abdulrahman Alsoghayer example.
import {Component} from '@angular/core';
import {timer} from 'rxjs';
@Component({
selector: 'my-app',
template: 'Ticks (every second) : \{\{ticks}}'
})
export class AppComponent {
ticks =0;
ngOnInit(){
let timer$ = timer(2000,1000);
timer$.subscribe(t=>this.ticks = t);
}
}