我意识到一个即时信使。当我点击一个帖子时,应该打开一个窗口,并进行所需的讨论。我不希望用户打开两个相同的讨论。这就是我为每个线程添加一个布尔'isOpen'变量的原因:
export class Thread {
id: string;
messages: Observable<Message[]>;
lastMessage: Message = null;
participants: User[];
isOpen: boolean;
isReduce: boolean;
isFlash: boolean;
constructor(id?: string,
participants?: User[],
messages?: Observable<Message[]>,
obj?: any) {
this.id = id || uuid();
this.participants = participants;
this.messages = messages;
this.isOpen = obj && obj.isOpen || false;
this.isReduce = obj && obj.isReduce || false;
this.isFlash = obj && obj.isFlash || true;
}
}
当我点击一个线程时,变量'thread.isOpen'变为true。 当我关闭这个线程时,变量'thread.isOpen'变为false:
export class ListItemComponent implements OnInit {
@Input() thread: Thread;
............................
clicked(thread: Thread): void {
this.newWindow = true;
if (!thread.isOpen) {
thread = this.chatService.openThread(thread);
this.chatService.setCurrentThread(thread);
thread.isOpen = true;
}
}
export class WindowItemComponent implements OnInit {
@Input() thread: Thread;
..............................
closeThread(thread?: Thread): void {
document.getElementById('chat-window-' + this.thread.id).style.display = 'none';
thread.isOpen = false;
this.newUser = false;
this.newWindow = false;
}
我不明白为什么它不起作用。当我测试我的变量时,这不会将初始化设置为true。我的两个功能分为两个不同的部分。
/////////////////////////////////////////////// // 修改
@Injectable()
export class ChatService {
openThread(thread: Thread): Thread {
const newThread: Thread = new Thread(thread.id, thread.participants, thread.messages);
this.threadService.windows.push(newThread);
return newThread;
}
setCurrentThread(newThread: Thread): void {
this.threadService.currentThread.next(newThread);
}
答案 0 :(得分:1)
我要粘贴和示例,我希望这会有所帮助。
想象一下,你有一个带有一些假线程的父组件,这些假线程可能来自实时的休息呼叫:
export class ParentComponent implements OnInit {
private threads: any[] = [{isOpen: false, id: '1'}, {isOpen: false, id: '2'}];
}
用它的html将对象传播给它的childdren:
<div>
<child *ngFor="let thread of threads" [thread]="thread"></child>
<child *ngFor="let thread of threads" [thread]="thread"></child>
<div *ngFor="let t of threads">{{t.isOpen}} </div>
</div>
执行此操作并更改其childdren中的线程对象时。线程对象将在父级和所有其他子级中随处更改。
子组件是这样的(它是一个非常简单的子项,显示isOpen属性,并使用change方法将其从false更改为true):
export class child implements OnInit {
@Input()
public thread: any;
public change(){
this.thread.isOpen = true;
}
}
使用html:
<div (click)="change()">{{thread.isOpen}}</div>
希望有所帮助。正如你所看到的,我试图证明你改变isOpen属性并不重要,它会影响应用程序中的任何地方