问题描述
您好,我已经开发了用户服务,该用户服务的工作是在与它们没有关系的组件之间共享数据。如果我要从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 (将#修改为@)