【发布时间】:2018-07-18 10:22:26
【问题描述】:
#headerComponent 中是我搜索的输入字段。当用户执行搜索时,搜索查询由#websocketsService 发送到节点服务器并返回 JSON 结果。
这个结果应该触发#graphComponent的方法。
我读到有另一个服务来处理这个是一个好习惯,所以我为此创建了#dataService,这是我处理可观察对象的地方。
所以流程是:
headerComponent -> (triggers) #websocketService -> (search query to) node.js-Server -> (result back to) #websocketService -> (set var in) #dataService -> (触发方法) #graphcomponent(来自#dataService 的新数据)
一切正常,除了我无法触发#graphComponent 中的方法。
数据服务
import { Injectable, EventEmitter, Output } from '@angular/core';
import { Subject } from 'rxjs/Subject';
import { Observable } from 'rxjs/Observable';
/**
* This Service is for keep, simple and small Data sharing
* to communicate between components
*/
@Injectable()
export class DataService {
private subject = new Subject<any>();
public setGraphData(data) {
console.log('setGraphData:' + data);
this.subject.next({text: data});
}
public getGraphData(): Observable<any> {
console.log('get graphDataSubject');
return this.subject.asObservable();
}
constructor() { }
}
图形组件
import { Component, OnInit} from '@angular/core';
import { Subject } from 'rxjs/Subject';
import { Subscription } from 'rxjs/Subscription';
import { DataService } from '../../../services/data/data.service';
import { Observable } from 'rxjs/Observable';
@Component({
selector: 'graph',
templateUrl: './graph.component.html',
styleUrls: ['./graph.component.scss'],
providers: [DataService]
})
export class GraphComponent implements OnInit{
graphData: Observable<any>;
subscription: Subscription;
constructor( private _dataService: DataService ) { }
ngOnInit() {
this._dataService.getGraphData().subscribe(graphData => {
console.log('PLEASE TRIGGER ME WHEN graphData IS UPDATED');
});
}
// PLEASE TRIGGER THIS FUNCTION WHEN NEW graphData IS SET
triggerMe() {
console.log('WORKS')
}
}
websocket服务
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';
import { DataService } from '../data/data.service';
@Injectable()
export class WebsocketsService {
private _search: string;
private url: string;
public wsConnection: WebSocket;
constructor(private _dataService: DataService) {
this.url = 'ws://localhost:1337';
}
/*
* creates connection, sends query and maps ws-handler
*/
sendQuery(search: string) {
this._search = search;
console.log('Perform search for: ' + this._search);
this.wsConnection = new WebSocket(this.url);
this.wsConnection.onopen = () => this.wsConnection.send(JSON.stringify({ data: this._search }));
this.wsConnection.onerror = event => console.log('A Error has occured!');
this.wsConnection.onclose = event => console.log('Connection closed');
this.wsConnection.onmessage = (event) => {
// SEND NEW DATA TO OBSERVABLE
this._dataService.sendGraphData(event.data);
};
}
}
我只是无法让它运行,当在#dataService 中设置新的graphData 时,会触发#graphComponent 中的triggerMe()。
【问题讨论】:
标签: angular components observable