【问题标题】:how to clear “distinct” RxJS operator in Angular 2?如何在 Angular 2 中清除“不同”的 RxJS 运算符?
【发布时间】:2017-07-08 04:52:20
【问题描述】:

有没有办法清除 distinct() 缓存?

如您所见,有时我设置 this.messages=[],此时我想清除缓存。相反,我做了一个 hack,我增加了 distinctCount。

ngOnInit() {
    let saved = {}
    let distinctCount = 1000000000000
    let messageStream = this.route.params
            .map(params=>params['id'])
            .switchMap((id)=> {
                this.messages = []
                saved[this.id] = this.newMessage
                this.id = id
                distinctCount+=1000000000000
                this.newMessage = saved[id] || ''
                return Observable.interval(3500).startWith(0).switchMap(()=> {
                    let count = 5
                    if (this.messages.length == 0) {
                        count = 10
                    }
                    return this.conversationsApi.apiConversationsByConversationIdGetMessagesGet(this.id, this.authService.getAuth(), undefined, count, undefined, undefined, undefined)
                })
            })
            .concatMap((messages:Array<MessageModel>)=>{
                return Observable.from(messages.slice().reverse())
            })
            .distinct(message=>message.id+distinctCount)
}

【问题讨论】:

    标签: angular rxjs angular2-observables


    【解决方案1】:

    最终得到了一个很好的解决方案,只需将 this.route.params observable 作为第二个参数传递给 distinct()。

    第二个参数是一个flush observable,当observable发出时distinct刷新它的缓存

    因此,每当用户在对话之间导航时,缓存都会刷新。

        ngOnInit() {
                let saved = {}
                let messageStream = this.route.params
                        .map(params=>params['id'])
                        .switchMap((id)=> {
                            this.messages = []
                            saved[this.id] = this.newMessage
                            this.id = id
                            this.newMessage = saved[id] || ''
                            return Observable.interval(3500).startWith(0).switchMap(()=> {
                                let count = 5
                                if (this.messages.length == 0) {
                                    count = 10
                                }
                                return this.conversationsApi.apiConversationsByConversationIdGetMessagesGet(this.id, this.authService.getAuth(), undefined, count, undefined, undefined, undefined)
                            })
                        })
                        .concatMap((messages:Array<MessageModel>)=>{
                            return Observable.from(messages.slice().reverse())
                        })
                        .distinct(message=>message.id, this.route.params)
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-12-12
      • 2019-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多