如何从Angular 8中的Observable获取最后一个值?
let test = new BehaviorSubject<any>('');
test.next(this.AddressObservable);
let lastValue = test.subscribe(data=>console.log(data.value));
由于某种原因,它无法正常工作,请检查调试器。
但是,这在html中有效, AddressObservable | async
试图利用此链接,要在变量中存储值或在控制台日志中显示。任何较新的语法都将有所帮助。
注意:
AddressObservable
类型: Observable<AddressDto>
您对这里的行为主题及其对您有什么影响感到有些困惑。
主题实际上是可以订阅的来自某些来源的价值流。每当发出新值时,它就会到达您的订阅方法中。
如果您具有初始状态,则可以使用行为主题来初始化主题,并确保新订户始终收到一个值。
如果您没有初始状态,但是想要确保新订阅者在订阅时获得最后发出的值(如果存在),则可以使用重播主题。
包含在主题中的所有值均为T类型Subject<T>
。因此,在您的情况下,进入主题的所有内容都应为AddressDto
。
如果您有一个初始地址,则可以这样设置行为主题:
// somehow get my initial address
const address = new AddressDto(); //
const test = new BehaviorSubject<AddressDto>(address);
// all subscribers will receive this address upon subscribing
// ... some things happen
// now I have another address, emit that
const newAddress = new AddressDto();
test.next(newAddress);
// all new subscribers will now receive newAddress upon subscribing
另一方面,如果没有初始地址,则可以使用以下重放主题:
// always emit the last address to new subscribers by intitialing with a 1
// New subscribers won't receive an address until one is emitted
const test = new ReplaySubject<AddressDto>(1);
// ... some things happen
// now I have my first address, emit that
const firstAddress = new AddressDto();
test.next(firstAddress);
// all current subscribers receive firstAddress
// all future subscribers will receive firstAddress upon subscribing
// ... some things happen
const secondAddress = new AddressDto();
test.next(secondAddress);
// all current subscribers receive secondAddress
// all future subscribers will now receive secondAddress upon subscribing
编辑:
您询问有关将最后一个值存储在变量中的问题。您的意思含糊不清,因此我将假设您的意思是从源头上讲,因为这更加复杂。
一旦您掌握了主题/可观察的概念,便开始了解可观察管道的概念。各种各样的事情都可能在管道内发生-只需将其视为可能发生在对象上的一系列步骤即可,就像普通的javascript数组上的一系列链接数组函数一样。
您可以在管道中执行的tap()
操作之一是在操作员中执行“副作用” 。这仅意味着您可以在管道中间进行处理,同时让数据通过。这些事情之一可能是出于某种目的将值存储在变量(或本地存储或其他内容)中。
如果您可以控制进入主题的内容,那么在管道中执行此操作似乎是多余的,因此,我将使用缓存http请求结果的示例。
this.http.get(url).pipe(
// transform the http response into an object you have created
map(response => this.mapResponseToMyClass(response)),
// store the mapped object in a local property for later use
tap(myClass => {
// you can perform any side-effect actions you want here
console.log(myClass);
// store the value in a variable
this.cachedMyClass = myClass;
})
);
管道自己的主题没有什么不同-主题所涉及的所有内容都会通过管道,然后发送给订户。
private subject = new Subject<AddressDto>();
getPostcode(): Observable<string> {
// reuse the local subject. All subscribers to this function will receive addresses that have come through the pipe.
return subject.pipe(
map(address => address.postcode),
// store the last postcode in a local property
tap(postcode => this.lastPostcode = postcode)
// the postcode still comes out here to all subscribers
).asObservable();
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句