简体   繁体   English

在回调函数中可观察到-角度2

[英]Observable in a callback function - angular 2

I am trying to implement a callback function in a service class, which has to return data back to the component class. 我正在尝试在服务类中实现回调函数,该服务类必须将数据返回给组件类。

ChatComponent.ts 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. 我已经看到了使用Http Observable回调的示例。 Here I've added my callback explicitly using addHandler. 在这里,我使用addHandler显式添加了回调。 I will get the message object in the 'onMessageReceivedHandler' method. 我将在“ onMessageReceivedHandler”方法中获取消息对象。 But i need to pass it to ChatComponent. 但是我需要将其传递给ChatComponent。 How can I pass the data. 如何传递数据。

I think Carsten is right you can use subject and Behavior Subject to get your received massage 我认为Carsten是对的,您可以使用主题和行为主题来获得您的按摩

In service file 在服务档案中

message:Subject<string> = new Subject();

    broadcastMessage(text:string) {
        this.message.next(text);
    }

and In component file you can subscribe to the message subject 在组件文件中,您可以订阅消息主题

this. _chatService.message.subscribe((msg) => {
  console.log(“Message received from chat service class”+msg);
});

You can use a Subject for this. 您可以为此使用主题。

In ChatService: 在ChatService中:

subscribers: Subject[] = [];

then in joinChat 然后在joinChat中

joinChat(userSubject: Subject) {
  this.subscribers.push(userSubject);
}

then in messageReceivedHandler: 然后在messageReceivedHandler中:

for (let i = 0; i < this.subscribers.length(); i++) {
  this.subscribers[i].next("Hello");
}

ChatComponent: 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.. 请注意:我是从脑海写的,所以不能保证代码可以编译。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM