对不起,我确定这是关于角度的最常见问题之一,我发现了很多,但没有任何帮助。我有一个简单的Observable-带变量的订阅关系。
我的服务:
activeRoom: number = 0; // we're starting in room 0
/* get the roomnumber from open-rooms to chat-window */
getActiveRoom(): Observable<number> {
return of(this.activeRoom);
}
我的组件:
constructor(
private activeRoomService: ActiveRoomService){}
ngOnInit() {
/* Observe if we're changing rooms */
this.activeRoomService.getActiveRoom().subscribe(newActiveRoom => {
this.activeRoomChat = []; // clear the message board
this.activeRoom = newActiveRoom;
});
}
click(){
console.log("the following line doesn't work");
console.log(this.activeRoom);
console.log("the following line does work")
console.log(this.activeRoomService.activeRoom);
}
很明显,我每次都无法单击来更新组件,因此选项b是不可选的:D
我在这里想念的最明显的事情是什么?
这是一个可行的例子。
服务:
private userArray: User[] = [];
getUserArray(): Observable<User[]>{
return of(this.userArray);
}
组件:
constructor(private backend: BackendService) {}
ngOnInit() {
this.backend.getUserArray().subscribe(user => {
this.userlist = user;
// console.log(user);
});
有人可以用一个非常大的红色箭头指向我在这里丢失的东西吗?
答案 0 :(得分:1)
已更改
activeRoom: number = 0;
getActiveRoom(): Observable<number> {
return of(this.activeRoom);
}
setActiveRoom(roomID): void {
this.activeRoom = roomID;
}
收件人:
activeRoom: Subject<number> = new Subject;
public getActiveRoom(): Observable<number> {
return this.activeRoom.asObservable();
}
public setActiveRoom(roomID): void {
this.activeRoom.next(roomID);
}
,并且有效。老实说,我不知道为什么或改变了什么,但我很高兴它起作用:D