【发布时间】:2018-07-12 12:21:19
【问题描述】:
很抱歉,我确定这是有关 Angular 的最常见问题之一,我找到了很多,但在这里没有任何帮助。我得到了一个简单的 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);
});
有人可以用一个非常大的红色箭头指向我在这里缺少的东西吗?
【问题讨论】:
-
我不明白你的问题是什么
-
变量 this.activeRoom 在服务中更新时不会在组件中更新。我可以肯定地说该服务会更新组件,因为我可以通过 this.activeRoomService.activeRoom 直接访问它。所以断开的链接在订阅和 getter 之间。
-
如果你打印它,它包含什么 newActiveRoom?好像省略了一些代码,activeRoom在哪里更新?
-
不完全确定我的问题是否正确。 newActiveRoom 是 getActiveRoom() 函数的返回语句。该函数本身返回一个 Observable
,但在语句中,newActiveRoom 是数字本身,然后将其传输到 this.activeRoom。例:它不是。 activeRoom 的设置器不是问题,因为它正在使用直接链接,但我可以告诉你两行: setActiveRoom(roomID): void { this.activeRoom = roomID; } -
所以 newActiveRoom 总是 0?