我有一个要修改的观察对象。
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'}, .....]
}
我想向message数组添加一个新消息,例如:{id = 3,comments:'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)
,但它只是添加了一个新对象
预先谢谢你
答案 0 :(得分:0)
在使用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 );
所以您将获得所有三个对象