I am trying to implement a callback function in a service class, which has to return data back to the component class.
ChatComponent.ts
export class ChatComponent implements OnInit {
constructor( public _chatService : ChatService) {
_chatService.joinChat()
}
OnInit(){
}
// I need to get the `msg` object from the ChatService class
didReceiveMessage(msg){
console.log(“Message received from chat service class”+msg);
}
}
ChatService.ts
import { Component, Input } from '@angular/core';
import { Injectable } from '@angular/core';
@Injectable()
export class ChatService {
public chatObj : SomeChatObject;
constructor() { }
joinChat(){
//Join chat related functionality
this.chatObj.addHandler(this.onMessageReceivedHandler, null, "message");
}
onMessageReceivedHandler = (message) => {
//Send `message` back to `didReceiveMessage ` method in ChatComponent.ts
return true;
}
}
I’ve seen an example of using Http Observable callback. Here I’ve added my callback explicitly using addHandler. I will get the message object in the ‘onMessageReceivedHandler’ method. But i need to pass it to ChatComponent. How can I pass the data.
You can use a Subject for this.
In ChatService:
subscribers: Subject[] = [];
then in joinChat
joinChat(userSubject: Subject) {
this.subscribers.push(userSubject);
}
then in messageReceivedHandler:
for (let i = 0; i < this.subscribers.length(); i++) {
this.subscribers[i].next("Hello");
}
ChatComponent:
constructor( public _chatService : ChatService) {
let subject = new Subject();
subject.subscribe(
msg => console.log(msg);
);
_chatService.joinChat(subject);
}
Take note: i wrote this from my head so no guarantees that the code compiles..