将对象数组作为可观察对象从服务传递到组件

时间:2017-03-20 00:08:29

标签: angular typescript angular2-observables

我正在尝试将消息数据从服务传递到组件中作为observable。在组件中我想订阅数据。我尝试了很多方法,但它没有用。如何将对象数组作为可观察对象传递?我希望它应该工作。

目前我在浏览器中收到错误:

  

TypeError:this.chatService.getMessages(...)。subscribe不是   功能

message.component.ts

    import {
     Component,
     Input,
     OnInit,
     Output,
     EventEmitter,
     HostListener,
     ElementRef,
     Injectable
 } from "@angular/core";
 import {
     ChatService
 } from '../../service/chat.service';
 import * as sio from 'socket.io-client';
 import {
     Http,
     Headers,
     RequestOptions
 } from "@angular/http";
 import {
     Observable
 } from 'rxjs/Observable';
 import 'rxjs/add/operator/map'
 @Component({

     selector: "messages",
     templateUrl: './messages.component.html'

 })
 @Injectable()
 export class MessagesComponent implements OnInit {
     connection;

     ngOninit() {

         this.connection = this.chatService.getMessages().subscribe(message => {
                 console.log(message)
             }

this.chatService.createMqttConnection(this.userId);



         }


   sendMessage(data:Object){

     //let data = {'msg':message, '_receiverId':receiverId, '_senderId':senderId}

      this.http.post('/messages/sendmessage',data).map((res: any) => res.json()).subscribe((res: any) => {
        // console.log('###################')
        // console.log(res)
        // console.log('###################')
         this._client.subscribe("sendmessage");

            var msg =  new Paho.MQTT.Message(JSON.stringify(res));

          msg.destinationName = "sendmessage";

         this._client.send(msg);

      },
      (error: any) => {
        console.log(error);
      }
     );



   }

     }

chat.service.ts

    import {
     Subject
 } from 'rxjs/Subject';
 import {
     Observable
 } from 'rxjs/Observable';
 import * as sio from 'socket.io-client';
 import {
     Injectable
 } from '@angular/core';
 import {
     Http,
     Headers,
     RequestOptions
 } from "@angular/http";
 import 'ng2-mqtt/mqttws31.js';

 declare
 var Paho: any;


 @Injectable()
 export class ChatService {
     private _client: any = "";
     public messageData: any = []; //--> [object, object]

     constructor(private http: Http) {

         this._client.onMessageArrived = (message: any) => {
             console.log('Message arrived.' + message);
             this.messageData.push(JSON.parse(message.payloadString));
             console.log(this.getMessages())
         };
     }



     getMessages() {

         return this.messageData;
     }
 }

解决方案:

我用特殊类型的可观察“主题”来解决它。我真的不明白为什么它不适用于Observable

我首先创建了一个对象

chat.service.ts

let printmessage = new Subject<any>(); 

this.printmessage.next(message);

message.component.ts

this.connection = this.chatService.printMessage.subscribe(message => {

console.log('Message: ' + message.message)
});

2 个答案:

答案 0 :(得分:1)

您的服务应该是这样的(概念性思考):

import { Subject } from 'rxjs/Subject';
import { Observable } from 'rxjs/Observable';
import * as sio from 'socket.io-client';
import { Injectable} from '@angular/core';
import { Http, Headers, RequestOptions } from "@angular/http";
import 'ng2-mqtt/mqttws31.js';

 declare let Paho: any;

 @Injectable()
 export class ChatService {
     private _client: any = "";
     public messageData: any = []; //--> [object, object]

     constructor(private http: Http) {

     }
     //Remember this will keep pushing items in your array as they arrive 
     //and keep returning messageData array
     getMessages():Observable<messageData> {
         this._client.onMessageArrived = (message: any) => {
             console.log('Message arrived.' + message);
             this.messageData.push(JSON.parse(message.payloadString));  
         };

        return this.messageData;
     }
 }

然后你不需要组件中的@Injectable()。以下是构造函数和ngOnInit的外观:

constructor(private chatService: ChatService) {

    }

    ngOnInit() {
        this.connection = this.chatService.getMessages().subscribe(message => {
        //here message is the array                     
        console.log(message)
             }
     }

希望这会有所帮助。

答案 1 :(得分:0)

聊天service.ts:

//import Observable:
import { Observable } from 'rxjs/Rx';
...
...
...

getMessages() {
    return Observable.create(observer => {
        observer.next(this.messageData);
        observer.complete();
    });

}