具有手动刷新能力的 ActivatedRoute observable
ActivatedRoute observable with manual refresh ability
我目前正在开发一个 Angular 需要手动“从服务器重新获取”功能的组件。
下面列出的版本可以使用,但有什么方法可以简化它吗?看起来有点复杂。
private refreshSignalSubject = new Subject<any>();
refreshSignal$: Observable<any> = this.refreshSignalSubject.asObservable();
ngOnInit() {
this.item$ = combineLatest(
this.route.paramMap.pipe(
map(params => params.get('id')),
),
this.refreshSignal$.pipe(
startWith(() => Math.random())
)
).pipe(
map((values) => {
const [id, _] = values
return id
}),
switchMap(id => this.apiService.get(`/items/${id}`)),
share()
)
}
reloadItem() { // this method is triggered from the view and from other methods in this component
this.refreshSignalSubject.next(Math.random());
}
你甚至不需要把它放在ngOnInit
:
readonly items$ = combineLatest([
this.route.params.pipe(
map(({ id }) => id),
distinctUntilChanged()
),
this.refreshSignal$
]).pipe(
switchMap(([ id ]) => this.apiService.get(`/items/${id}`)),
shareReplay(1)
)
这应该够了
我目前正在开发一个 Angular 需要手动“从服务器重新获取”功能的组件。
下面列出的版本可以使用,但有什么方法可以简化它吗?看起来有点复杂。
private refreshSignalSubject = new Subject<any>();
refreshSignal$: Observable<any> = this.refreshSignalSubject.asObservable();
ngOnInit() {
this.item$ = combineLatest(
this.route.paramMap.pipe(
map(params => params.get('id')),
),
this.refreshSignal$.pipe(
startWith(() => Math.random())
)
).pipe(
map((values) => {
const [id, _] = values
return id
}),
switchMap(id => this.apiService.get(`/items/${id}`)),
share()
)
}
reloadItem() { // this method is triggered from the view and from other methods in this component
this.refreshSignalSubject.next(Math.random());
}
你甚至不需要把它放在ngOnInit
:
readonly items$ = combineLatest([
this.route.params.pipe(
map(({ id }) => id),
distinctUntilChanged()
),
this.refreshSignal$
]).pipe(
switchMap(([ id ]) => this.apiService.get(`/items/${id}`)),
shareReplay(1)
)
这应该够了