AIM: I send a http request from angular 2 ui to java server. While it is executing, server generates messages with progress status so I can update progress bar on ui.
I have 3 entities: AppComponent , AppService and WebsocketService . Here is a simplified example of WebsocketService . It can subscribe to message topic and perform some actions on incoming each message.
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
})
});
}
}
So, my question is: how to update AppComponent's property (field) value, which is binded to template, from AppService or even WebsocketService? Use a setter? Is it allright from the terms of MVC?
There is more than one way to do this but I would use a "Subject" stream.
Here is an example:
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;
});
}
}
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.