我正在尝试在服务类中实现一个回调函数,该函数必须将数据返回给组件类。
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;
}
}
我见过使用Http Observable回调的例子。在这里,我使用addHandler显式添加了我的回调。我将在'onMessageReceivedHandler'方法中获取消息对象。但我需要将它传递给ChatComponent。我如何传递数据。
答案 0 :(得分:2)
我认为Carsten是对的,你可以使用主题和行为主题来获得按摩
在服务档案
中message:Subject<string> = new Subject();
broadcastMessage(text:string) {
this.message.next(text);
}
并在组件文件中,您可以订阅邮件主题
this. _chatService.message.subscribe((msg) => {
console.log(“Message received from chat service class”+msg);
});
答案 1 :(得分:1)
您可以使用主题。
在ChatService中:
subscribers: Subject[] = [];
然后在joinChat
joinChat(userSubject: Subject) {
this.subscribers.push(userSubject);
}
然后在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);
}
请注意:我是从头开始写的,所以不能保证代码编译..