可以使用pairwise操作符来获取最新值和上一个值。示例代码如下:
import { Component, OnInit } from '@angular/core'; import { pairwise } from 'rxjs/operators';
@Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { numbers = [1, 2, 3, 4, 5]; ngOnInit(){ this.numbers.forEach(num => { this.watchValue(num); }) }
watchValue(num: number) {
const num$ = of(num).pipe(delay(1000));
num$.pipe(pairwise()).subscribe(([oldValue, newValue]) => {
console.log(Number changed from ${oldValue} to ${newValue}
);
});
}
}
在上面的代码中,我们使用了RxJS的pairwise操作符来获取值的新旧值,其中pairwise返回一个数组,该数组包含最新的值和上一个值。