以下两个可观察映射之间有什么区别?
(如果以下代码中的某些内容对您来说很奇怪:它源于一个边做边学的爱好项目;我仍然学习RxJS)
我有一个带有getter和构造函数的组件.两者都从应用程序的ngrx存储中读取信息并提取字符串(名称).
getter和构造函数之间的唯一区别:getter在HTML中使用,它返回的observable通过异步管道发送,而构造函数中的observable映射由订阅使用subscribe完成.我希望它们都可以随着名称的新值变得频繁而激活.
但是只有getter以这种方式工作并在HTML中提供异步管道,并在其中使用新的name值(每次更改名称时都会调用console.log(‘A’)).订阅订阅的回调只被调用一次:console.log(‘B’)和console.log(‘B!’)都被调用一次,而不再被调用.
如何解释这种行为差异?
我的组件的片段:
// getter works exactly as expected: get name$(): Observable<string> { console.log('getter called') return this.store .select(this.tableName,'columns') .do(_ => console.log('DO (A)',_)) .filter(_ => !!_) .map(_ => _.find(_ => _.name === this.initialName)) .filter(_ => !!_) .map(_ => { console.log('A',_.name) return _.name }) } // code in constructor seems to lose the subscription after the subscription's first call: constructor( @Inject(TablesStoreInjectionToken) readonly store: Store<TablesState> ) { setTimeout(() => { this.store .select(this.tableName,'columns') .do(_ => console.log('DO (B)',_)) .filter(_ => !!_) .map(_ => _.find(_ => _.name === this.initialName)) .filter(_ => !!_) .map(_ => { console.log('B',_.name) return _.name }) .subscribe(_ => console.log('B!',_)) }) }
附加信息:如果我添加ngOnInit,则在整个测试期间只调用一次生命周期挂钩.如果我将订阅从构造函数移动到ngOnInit生命周期钩子,它不会比在构造函数中更好地工作.完全相同(意外)的行为.这同样适用于ngAfterViewInit和其他生命周期钩子.
名称的输出更改’some-name’ – > ‘some-other-name’ – > ‘some-third-name’ – > ‘some-fourth-name’ – > “一些,第五名”:
[更新]正如Pace在评论中所建议的,我添加了getter通话记录
[UPDATE]根据Pace的建议添加了dos
getter called DO (A) (3) [{…},{…},{…}] A some-name DO (B) (3) [{…},{…}] B some-name B! some-name getter called DO (A) (3) [{…},{…}] A some-other-name getter called DO (A) (3) [{…},{…}] A some-third-name getter called DO (A) (3) [{…},{…}] A some-fourth-name getter called DO (A) (3) [{…},{…}] A some-fifth-name
[ { "name": "some-name" },{ "name": "some-other-name" },{ "name": "some-third-name" } ]
从ngrx.select()返回的Observable只会在商店中的数据发生变化时触发.
如果你希望在initialName更改时触发Observable,那么我建议将initialName转换为RXJS主题并使用combineLatest:
initialNameSubject = new BehaviorSubject<string>('some-name'); constructor( @Inject(TablesStoreInjectionToken) readonly store: Store<TablesState> ) { setTimeout(() => { this.store .select(this.tableName,'columns') .combineLatest(this.initialNameSubject) .map(([items,initialName]) => items.find(_ => _.name === initialName)) .filter(_ => !!_) .map(_ => { console.log('B',_)) }) }