I have an angular service and two different unrelated components that use this service:
Service Code:
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);
}
}
Component 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 ..
Component 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 ..
I get the following output in the console:
comp1
comp1 - after subscribe
comp2 - after subscribe
the output I think I should get:
comp1
comp1 - after subscribe
comp2
comp2 - after subscribe
Can anyone explain what the problem is?
Note: I added my service to the Module providers and got the same result.
Thanks.
here's the code for webSocketService: https://github.com/elliotforbes/ng-chat/blob/master/src/app/common/services/websocket.service.ts