在Angular中使用RxJS中的订阅机制来实时更新变量值。
首先,在组件中声明RxJS的Observable类型变量,并使用ngOnInit方法来订阅它:
import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.css']
})
export class MyComponent implements OnInit {
myObservable$: Observable;
constructor() { }
ngOnInit() {
this.myObservable$ = new Observable(observer => {
setInterval(() => {
observer.next(new Date().toString()); // 发出新值
}, 1000);
});
}
}
然后,在模板中使用async管道来实时显示Observable中发出的新值:
{{ myObservable$ | async }}
这样,每秒钟组件的模板就会更新一次,显示最新的日期值。
注意:在组件销毁时,应该取消订阅以避免内存泄漏:
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Observable, Subscription } from 'rxjs';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.css']
})
export class MyComponent implements OnInit, OnDestroy {
myObservable$: Observable;
subscription: Subscription;
constructor() { }
ngOnInit() {
this.myObservable$ = new Observable(observer => {
this.subscription = setInterval(() => {
observer.next(new Date().toString()); // 发出新值
}, 1000);
});
}
ngOnDestroy() {
this.subscription.unsubscribe(); // 取消订阅
}
}