【问题标题】:Cache emited value when using async pipe to be able to filter out future emits使用异步管道时缓存发出的值以便能够过滤掉未来的发出
【发布时间】:2020-09-02 13:52:23
【问题描述】:

我正在尝试缓存 observable 的发射值,以过滤掉不相关的未来发射。

我有一条路线:

{ path: "user/:id/:type", component: UserComponent }

在该组件中,我将 ActivatedRoute 参数、switchMap 获取到实际的 http 调用,并在模板上使用 async 管道来显示用户详细信息。

user$: Observable<User>;

ngOnInit() {
    this.user$ = this.route.params.pipe(
       switchMap(params => {
         return this.http.getUser(params.id)
       })
    );
}

在它自己的模板中:

<div *ngIf="user$ | async as user"> 
   <span>{{ user.id }}</span>
   <span>{{ user.name }}</span>
</div>

如果路由改变但:id 参数保持不变,我想过滤掉this.route.params 值。

我在想类似的事情

user$: Observable<User>;

ngOnInit() {
    this.user$ = this.route.params.pipe(
       withLatestFrom(this.user$ || Observable.from({})),
       filter( ([params, user]) => {
           return (params.id !== user.id); // filter if params id equals to last fetched user
       }),
       switchMap(params => {
         return this.http.getUser(params.id)
       })
    );
}

withLatestFrom 出现空值。 我想避免使用水龙头操作符缓存它,而只是想出一个干净的替代方案,就像我试图走的路一样。我错过了什么?

【问题讨论】:

    标签: angular rxjs behaviorsubject


    【解决方案1】:

    要仅将值与最后一个发射进行比较,您可以使用 RxJS 的 pluck 运算符选择 id 属性和 distinctUntilChanged 运算符来忽略通知,直到 id 被更改。

    试试下面的

    ngOnInit() {
        this.user$ = this.route.params.pipe(
           pluck('id'),
           distinctUntilChanged(),
           switchMap(id => {
             return this.http.getUser(id)
           })
        );
    }
    

    或者要忽略所有重复项并仅针对不同的ids 触发 HTTP 请求,您可以使用 RxJS distinct 运算符。

    ngOnInit() {
        this.user$ = this.route.params.pipe(
           distinct(params => params['id']),
           switchMap(params => {
             return this.http.getUser(params.id)
           })
        );
    }
    

    【讨论】:

    • 你是个天才。
    猜你喜欢
    • 2021-08-12
    • 1970-01-01
    • 2020-12-15
    • 2023-04-01
    • 1970-01-01
    • 2019-05-08
    • 2021-05-02
    • 2020-08-12
    • 2012-10-13
    相关资源
    最近更新 更多