【问题标题】:how to update a nested observable ain angular 9?如何更新 Angular 9 中的嵌套 observable?
【发布时间】:2020-10-12 10:45:59
【问题描述】:

我有一个要修改的 observable。

private userProposalConversatorAfterLogin = new BehaviorSubject<any>([]);
    getUserProposalConversatorAfterLogin$ = this.userProposalConversatorAfterLogin.asObservable();
    currentUserProposalConversatorAfterLoginValue():ParcelModel[] {
      return this.userProposalConversatorAfterLogin.value;
    }
    setUserProposalConversatorAfterLogin(x) {
      this.userProposalConversatorAfterLogin.next(x);
    }

这是订阅的结果(this.getUserProposalConversatorAfterLogin$.suscribe(proposal))

{
id:1,
messages:[{id:'1', comments:'hello'}, {id=2, comments:'aaa'}, .....]
}

我想在消息数组中添加一条新消息,例如:{id=3, cmets:'oooo'} 和 当我再次订阅时,我想得到:

  {
    id:1,
    messages:[{id:'1', comments:'hello'}, {id=2, comments:'aaa'},  {id=3, comments:'oooo'} .....]
    }

我尝试了很多方法,但没有成功

getUserProposalConversatorAfterLogin$.pipe(
    switchMap(x => {
      const new_array = (x.filter(x => x['id'] === proposal_identifiant))
      console.log(new_array);
      if (new_array && new_array.length >=1) {
        new_array[0]['message_proposal_identifiant'].push(new_message);
        console.log(new_array[0]['message_proposal_identifiant']);
        
      }
      return new_array

      }),
    share(),
    distinctUntilChanged(),
  )

当我再次订阅时,我看不到新值。我认为我们需要修改 userProposalConversatorAfterLogin 但如何修改?

我尝试使用this.userProposalConversatorAfterLogin.next(val),但它只添加了一个新对象 提前谢谢你

【问题讨论】:

  • 您好,给出的解决方案对您有帮助吗? ;)
  • 感谢我的朋友

标签: angular observable rxjs-observables


【解决方案1】:

当您使用BehaviorSubject 时,您可以在其上调用getValue(),它会为您提供当前值。并将当前值存储在变量中

例如:

const currentValue = this.userProposalConversatorAfterLogin.getValue(); 

// In your case current value is an array, so you can do below

currentValue.push( {id=3, comments:'oooo'} ); 

// and then call .next() with updated current value

this.userProposalConversatorAfterLogin.next( currentValue );

所以你会得到所有三个对象

工作Stackblitz

【讨论】:

    猜你喜欢
    • 2019-01-23
    • 2021-09-24
    • 2018-09-08
    • 2021-01-21
    • 2020-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-14
    相关资源
    最近更新 更多