我正在尝试在 angular 8 上使用 Observable.interval,但它似乎不喜欢它。
首先我导入 rxjs:
import { Observable } from 'rxjs';
Run Code Online (Sandbox Code Playgroud)
然后代码:
Observable.interval(1000).subscribe(x => {
// something
});
Run Code Online (Sandbox Code Playgroud)
什么是 angular 8 语法?
Mic*_*aud 13
你可以尝试这样的事情:
import { interval } from 'rxjs';
interval(1000).subscribe(x => {
// something
});
Run Code Online (Sandbox Code Playgroud)
小智 6
您可以使用如下所示的间隔。它也适用于 Angular12。
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();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9921 次 |
| 最近记录: |