Angular 2中的MVC - 从服务更新组件?

时间:2016-08-11 21:27:33

标签: model-view-controller angular

AIM:我从angular 2 ui向java服务器发送http请求。在执行时,服务器会生成具有进度状态的消息,因此我可以在ui上更新进度条。

我有3个实体: AppComponent AppService WebsocketService 。 以下是 WebsocketService 的简化示例。它可以订阅消息主题并对传入的每条消息执行一些操作。

export class WebsocketService {

    private client: Client;

    constructor() {
        var service = this;
        service.client = Stomp.client('ws://localhost:8080/stomp/websocket');

        service.client.connect("user", "pass", function () {
            service.client.subscribe("/progress", function (message) {
                // some actions here
            })
        });
    }
}

所以,我的问题是:如何从AppService甚至WebsocketService更新绑定到模板的AppComponent的属性(字段)值?使用二传手?从MVC的条款来看,它是否正常?

1 个答案:

答案 0 :(得分:2)

有多种方法可以做到这一点,但我会使用"主题"流。

以下是一个例子:

import {Injectable} from '@angular/core';
import {Http, Headers, RequestOptions, Response} from '@angular/http';
import {Observable} from 'rxjs/Rx';
import {Subject} from 'rxjs/Subject';
import {NextObserver} from 'rxjs/Observer';

export class WebsocketService {
    public ProcessingMessages$: Observable<string>;

    private client: Client;
    private processingMessages: Subject<string>;


    constructor() {
        this.processingMessages = new Subject<string>();
        this.ProcessingMessages$ = this.processingMessages.asObservable();

        var service = this;
        service.client = Stomp.client('ws://localhost:8080/stomp/websocket');

        service.client.connect("user", "pass", function () {
            service.client.subscribe("/progress", function (message) {
                this.processingMessages.next(message);
            })
        });
    }
}

// Sample Component
@Component({
    selector: 'my-component',
    template: 'WebsocketService Message: {{Message}}',
})
export class Sample Component implements OnInit {
    public Message: string;

    constructor(
        private service: WebsocketService
    ) {
    }

    ngOnInit() {
        this.service.ProcessingMessages$.subscribe((message: string) => {
            this.Message = message;
        });
    }
}