简体   繁体   中英

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

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.

I think Carsten is right you can use subject and Behavior Subject to get your received massage

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:

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..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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