Issue
Component A subscribes to an observable in Service B:
Component A:
testMqtt(){
console.log('testMqtt is called');
this.serviceB.connectToBroker().subscribe({
next: (resp) => console.log('response from connection to mqtt: ', resp.connected),
error: (err) => console.log('error from connection to mqtt: ', err)
});
}
Service B:
connectToBroker(){
let client = mqtt.connect(this.url, {clientId: 'abc123'});
return of(client.on('connect', (packet) => {
console.log('testing value of connected: ', JSON.stringify(packet));
console.log('value of client connected: ', client.connected);
}))
};
The idea is to reflect the value of 'client.connected' (Service B) in 'resp.connected' (Component A). Why does console.log from testMqtt() always show the value of resp.connected as false when the value of client.connected inside connectToBroker() in Service B is true? Which rxjs operator can I use in Service B that will allow the client.on callback to complete before returning a response to the subscription in Component A?
Solution
The code of the service is using a callback, so the code inside the function will execute and I dont think, the value will get emitted, after the callback is run, could you try using fromEvent
to create an observable listener instead!
connectToBroker(){
let client = mqtt.connect(this.url, {clientId: 'abc123'});
return fromEvent(client, 'connect').pipe(
tap(() => {
console.log('testing value of connected: ', JSON.stringify(packet));
console.log('value of client connected: ', client.connected);
}),
);
};
Answered By - Naren Murali
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.