【发布时间】:2020-06-21 02:18:20
【问题描述】:
我有一个 Angular 服务和两个不同的使用该服务的不相关组件:
服务代码:
const url = 'ws://localhost:8080
@Injectable({
provideIn: 'root',
})
export class MyService{
public subject: Subject<Status>;
constructor(wsService: WebSocketService){
this.subject = <Subject<Status>>wsService.connect(url).map(
(response: MessageEvent): Status => {
let data = JSON.parse(response.data);
return data;
}
);
}
getObs(){
return this.subject.asObservable();
}
sendMsg(msg){
this.subject.next(msg);
}
}
组件 1:
@Component
.. some irrelevant code ..
constructor(private service: MyService){
this.service.getObs().subscribe( data =>
console.log('comp1');
);
console.log('comp1 - after subscribe');
}
.. some irrelevant code ..
组件 2:
@Component
.. some irrelevant code ..
constructor(private service: MyService){
this.service.getObs().subscribe( data =>
console.log('comp2');
);
console.log('comp2 - after subscribe');
}
.. some irrelevant code ..
我在控制台中得到以下输出:
comp1
comp1 - 订阅后
comp2 - 订阅后
我认为我应该得到的输出:
comp1
comp1 - 订阅后
comp2
comp2 - 订阅后
谁能解释一下问题出在哪里?
注意:我将服务添加到模块提供程序并得到相同的结果。
谢谢。
这里是 webSocketService 的代码:https://github.com/elliotforbes/ng-chat/blob/master/src/app/common/services/websocket.service.ts
【问题讨论】:
-
wsService.connect(url)返回什么数据类型? -
WebSocketService是您创建的吗? -
MyService 没有任何明显的重放行为,组件 2 是否在触发组件 1 输出的消息之后开始订阅?
-
这里是 webSocketService 的代码:github.com/elliotforbes/ng-chat/blob/master/src/app/common/…
标签: angular service components observable subject