从服务器连续获取实时数据并在angular2中重新调整html中的更改

时间:2017-11-23 08:52:42

标签: angular

我正在尝试创建一个显示来自服务器的实时数据的实时仪表板。服务器上的实时数据意味着数据在服务器上不断变化。 我想跟踪更改并将其反映在我的仪表板模板上。

我想要最好的方法来满足要求。请帮忙。 虽然,我还没有开始研究这个仪表板。我将如何做到这一点如下。虽然对于angular2来说是个新手,但却没有什么想法来完成这个任务呢?请帮助您采用最佳方法。

service.ts

  import { Injectable } from '@angular/core';
    import { Http, Response, RequestOptions, Headers } from '@angular/http';
    import { Observable } from 'rxjs/Observable';
    import 'rxjs/add/operator/map';
    import 'rxjs/add/operator/catch';
    import 'rxjs/add/observable/throw';
    @Injectable()
    export class DataService {

      constructor(private http: Http) {
      }

 // here method of getting live data (changing continuosly on server)
// How to keep track of json data changes on server and pass it on component template


    getPIWSData(clientJson): Observable<any[]> {
     console.warn('Retriving Data from  Server' + JSON.stringify(clientJson));

    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });
    returnthis.http.post('http://10.40.10oardDatasingle', clientJson)
        .map(this.extractData)
        .catch(this.handleError);
    }

      private extractData(res: Response) {
        const body = res.json();
        return body || [];
      }

      private handleError(error: any) {
        const errMsg = (error.message) ? error.message :
          error.status ? `${error.status} - ${error.statusText}` : 'Server error';
        console.error(errMsg);
        console.log('Server Error!');
        return Observable.throw(errMsg);
      }
    }

dashboard.component.ts

@Component({
  selector: '',
  templateUrl: './.html',
  styleUrls: ['./acomponent.css']
})

name: string;

constructor( public jsonDataService: DataService){}
   this.jsonDataService.getPIWSData().subscribe(
          function (success) {
            this.data = success;
            this.getdata(success);
          },
          error => console.log('Getting Server Data Error :: ' + JSON.stringify(error)));

getdata(jsonData){
console.log(jsonData);

// Here, handling data
this.name  =  <----------------------from jsonData

}

dashboard.component.html

<div>{{name}} </div>     <----here name coming from server should change 
                       if there data changes

2 个答案:

答案 0 :(得分:0)

从可观察数据的性质来看,数据会在更改时更新,问题是post请求只返回一次。要实现您的目标,您需要更改服务器以使用套接字或类似技术。

答案 1 :(得分:0)

我会推荐WebSockets,我不知道你的后端是什么,所以我只给你一个前端的解决方案。

<强> websocket.service.ts

import { Observable } from 'rxjs/Rx';
import * as Rx from 'rxjs';
import { Injectable } from '@angular/core';


@Injectable()
export class WebsocketService {

    private subject: Rx.Subject<MessageEvent>;

    public connect(url: string): Rx.Subject<MessageEvent> {
        if (!this.subject) {
            this.subject = this.create(url);
        }
        return this.subject
    }

    private create(url: string): Rx.Subject<MessageEvent> {
        let ws = new WebSocket(url);

        let observable = Rx.Observable.create((obs: Rx.Observer<MessageEvent>) => {
            ws.onmessage = obs.next.bind(obs);
            ws.onerror = obs.error.bind(obs);
            ws.onclose = obs.complete.bind(obs);

            return ws.close.bind(ws);
        });

        let observer = {
            next: (data: Object) => {
                if (ws.readyState === WebSocket.OPEN) {
                    ws.send(JSON.stringify(data));
                }
            }
        };

        return Rx.Subject.create(observer, observable);
    }

}

<强> WS-object.ts

export class WsObject{
    constructor(
        public type: string,
        public data: any
    ) { }
}

<强> component.service.ts

@Injectable()
export class ComponentService {

    private websocketUrl= 'ws://backendurl';
    public messages: Subject<WsObject>;

    constructor(
        private websocketService: WebsocketService
    ) {
        this.messages = <Subject<WsObject>>websocketService.connect(this.websocketUrl).map((response: MessageEvent): WsObject=> {
        let data = JSON.parse(response.data);
        return data;
        }
    );
    }
}

<强> somemething.component.ts

@Component({
    selector: 'component',
    templateUrl: 'something.component.html'
})
export class SomethingComponent implements OnInit {
    constructor(
        private componentService: ComponentService ,
    ) {
        componentService.messages.subscribe(msg => {
            this.handleIncomingMessages(msg);
        });
    }

    handleIncomingMessages(msg) {
      //here comes the data on every change
    }
}