2017-05-31 114 views
1

我對angular 2相當陌生,並且堅持一個基本問題。angular 2如何將服務響應數據傳遞給UI

顯示的UI我的組件是這樣的: chat.ts

@IonicPage() 
@Component({ 
    selector: 'page-chat', 
    templateUrl: 'chat.html', 
    providers: [ChatService] 
}) 
export class ChatPage { 
items: SimpleMessage[] = []; 

createChatBubble(chatMessage: string){ 
    //alert(this.chatMessage); 
    this.items.push(new SimpleMessage(chatMessage)); 
    } 
} 

聊天service.ts

 @Injectable() 

      export class ChatService { 
      openSocket(){ 
       this.ws = new WebSocket('ws://' + this.host + '/chat/ws'); 
       this.ws.addEventListener('message', event => { 
        this.zone.run(() => { 
        var msg = JSON.parse(event.data); 
        this.broadcast(msg); 
        }); 
       }); 


    broadcast(msg){ 
     let message = this.parseModel(msg); 
     let chatReply = new SimpleMessage(message, 'bot'); 
    } 
} 

所以,從服務器中broadbast功能需求收到消息以某種方式傳遞給chat.ts項目對象。請告知

回答

0

您可以使用服務和您從組件訂閱的observable。

編輯: 我寫了另一個例子。 我不會寫一個套接字,但我寫了一個子組件,它觸發點擊按鈕上的某個事件。整個應用程序可以下載here

服務

import {Injectable} from '@angular/core'; 
import {Subject} from 'rxjs/Subject'; 

@Injectable() 
export class CommunicateService { 

    // source of change 
    private newStringSource = new Subject<string>(); 

    // observable 
    public stringCreated = this.newStringSource.asObservable(); 

    public sendNewString(newString: string): void { 
    // broadcasts the new data to every listener 
    this.newStringSource.next(newString); 
    } 
} 

應用組件

import {Component, OnInit} from '@angular/core'; 
import {CommunicateService} from './communicate.service'; 

@Component({ 
    selector: 'app-root', 
    template: `<h1> 
    {{title}} 
    <app-child></app-child> 
    </h1> 
    ` 
}) 
export class AppComponent implements OnInit { 

    title = 'app works!'; 


    constructor(private communicateService: CommunicateService) { 
    } 

    ngOnInit(): void { 
    this.communicateService.stringCreated.subscribe(event => { 
     console.log(event); 
    }); 
    } 
} 

孩子與一個按鈕觸發

import {Component, OnInit} from '@angular/core'; 
import {CommunicateService} from '../communicate.service'; 

@Component({ 
    selector: 'app-child', 
    template: `<p> 
    child works! 
    <button (click)="onClick()"> Click me </button> 
    </p> 
    ` 
}) 
export class ChildComponent { 

    constructor(private communicateService: CommunicateService) { 
    } 

    onClick() { 
    for (var i = 0; i < 10; i++) 
     this.communicateService.sendNewString(`i is ${i}`); // string interpolation 
    } 
} 

所以,你想要做的是什麼,而不是注入的服務到子補償這裏,將其注入套接字服務並在您接收新數據時調用sendNewString。

希望它有幫助。

+0

都需要componentChangeSource和newDateCreationSource還是隻需要兩個不同的變體? – Vik

+0

只是不同的變化,顯示不一定需要傳遞一些數據。 – LLL

+0

其中componentChanged $在服務中聲明?這到底意味着什麼? – Vik