如何解决BehaviorSubject下一个方法不更新其他组件的更改
您好,我已经开发了用户服务,该用户服务的工作是在与它们没有关系的组件之间共享数据。如果我要从Peoplecompoent更改数据,则inboxcomponent不会检测到它。 在这里,我正在为我的服务申请代码。
import { Injectable } from '@angular/core';
import { BehaviorSubject,Observable } from 'rxjs';
import {UserModel } from '../Models/UserModel';
@Injectable({
providedIn: 'root'
})
export class UserService {
public messageSubject$ : BehaviorSubject<UserModel[]> = new BehaviorSubject(null);
public users : UserModel[]=[];
constructor() {
for(var i =0 ;i<=6;i++){
var user = new UserModel();
user.userId = i.toString();
user.userName = 'Ashok Kumar';
user.userInterest = i.toString();
user.isActiveInbox = false;
user.isActiveCurrent = false;
this.users.push(user);
}
this.messageSubject$.asObservable();
}
getUser(): Observable<UserModel[]> {
return this.messageSubject$.asObservable();
}
addUser(){
var user = new UserModel();
user.userId = '7';
user.userName = 'Ashok Kumar';
user.userInterest = '7';
user.isActiveInbox = true;
user.isActiveCurrent = true;
this.users.push(user);
}
changeUser(){
this.messageSubject$.next(this.users);
}
activeForInbox(userId: string){
var user = this.users.find(x=> x.userId==userId);
user.isActiveInbox = true;
this.messageSubject$.next(this.users);
console.log(this.users);
}
}
在人员组件中,我已通过activeForInbox方法更改了消息。
export class PeoplesComponent implements OnInit {
public users : UserModel[]=[];
public userService : UserService;
constructor(peopleService : PeopleService,userService : UserService) {
this.userService = peopleService;
this.userService.getUser().subscribe(users => this.users = users);
this.userService.changeUser();
}
activeForInbox(userId: string){
var user = this.users.find(x=> x.userId==userId);
user.isActiveInbox = true;
this.userService.messageSubject$.next(this.users);
console.log(this.users);
//this.userService.activeForInbox(userId);
// console.log(userId);
}
ngOnInit(): void {
}
}
我希望这些更改应在收件箱组件中检测到。
export class InboxPeopleComponent implements OnInit {
public users : UserModel[]=[];
public userService: UserService;
constructor(inboxService : InboxService,userService : UserService) {
this.userService = userService;
userService.getUser().subscribe(users => this.users = users);
userService.changeUser();
// setTimeout(() => {
// userService.getUser().subscribe(users => this.users = users);
// userService.changeUser();
// console.log(this.users);
// },5000);
}
showdata(){
this.userService.getUser().subscribe(users => this.users = users);
// this.userService.changeUser();
console.log(this.users);
}
ngOnInit(): void {
//this.userService.changeUser();
}
}
当我从peoplecompoent调用activeForInbox方法时,inboxcompoent无法检测到更改
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。