要检测或获取Angular 4中的订阅后的旧值,可以使用rxjs的pairwise
操作符。以下是一个包含代码示例的解决方法:
import { pairwise, startWith } from 'rxjs/operators';
import { Component } from '@angular/core';
export class MyComponent {
oldValue: any;
ngOnInit() {
// 创建一个Observable对象
const myObservable = ... // 替换为你的Observable对象
// 使用pairwise操作符获取旧值和新值的对
myObservable.pipe(
startWith(null), // 在订阅之前添加一个初始值
pairwise()
).subscribe(([oldValue, newValue]) => {
this.oldValue = oldValue;
console.log('旧值:', oldValue);
console.log('新值:', newValue);
});
}
}
在上述代码中,我们使用pairwise
操作符将Observable的值转换为旧值和新值的对。使用startWith
操作符添加一个初始值,以便在订阅之前获取到旧值。
请注意,你需要将...
替换为你自己的Observable对象。
通过这种方式,你就可以在订阅后获取到旧值和新值,并将旧值存储在组件的oldValue
属性中。