Angular5 Observables无效

时间:2018-02-08 00:18:15

标签: angular components observable

#headerComponent是我搜索的输入字段。当用户执行搜索时,搜索查询将由#websocketsService发送到节点服务器并返回JSON结果。

此结果应触发#graphComponent

的方法

我已经读过,使用另一个服务来处理这个是一个好习惯,所以我为此创建了#dataService,这是我处理observable的地方。

所以流程是:

headerComponent - > (触发器)#websocketService - > (搜索查询)node.js-Server - > (结果回到)#websocketService - > (set var in)#dataService - > (触发方法)#graphcomponent(来自#dataService的新数据)

一切正常,但我无法在#graphComponent触发的方法中获得该方法。

的DataService

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() { }
}

graphComponent

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')
}       
}

websocketService

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()

1 个答案:

答案 0 :(得分:0)

问题在于您将Observable分配给Observable。

数据服务中的

graphData是一个Observable,在您的组件中,您将viewmodel属性graphData设置为服务返回的Observeable,它也是一个Observable。 p>

相反,您需要将viewmodel值类型设置为等于websocket将返回的值,例如stringobject,或者punt并使用any

我改变了一些名字,并为此创建了一个示例项目。以下是源代码的链接:https://1drv.ms/u/s!Aun50jHsxPB0gcd4emGcDqViLGbySw

数据服务保持不变,但我更改了套接字服务,以便在网络上点击回显服务进行演示:

import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';
import { DataService } from './data.service';

@Injectable()
export class SocketService {
  public wsConnection: WebSocket;

  url: string;

  constructor(private _dataService: DataService) {
    this.url = 'ws://echo.websocket.org/';
  }

 /*
  * creates connection, sends query and maps ws-handler
  */
  sendQuery(): void {

    this.wsConnection = new WebSocket(this.url);
    this.wsConnection.onopen = () => this.wsConnection.send('Test Message');
    this.wsConnection.onerror = event => console.log('A Error has occured!');
    this.wsConnection.onclose = event => console.log('Connection closed');
    this.wsConnection.onmessage = (event) => {
      this._dataService.setGraphData(event.data);
    };
  }
}

我只是利用Angular CLI在此示例组件中创建的app.component.ts来获取服务中的值:

import { Component, OnInit, OnDestroy} from '@angular/core';
import { Subject } from 'rxjs/Subject';
import { Subscription } from 'rxjs/Subscription';
import { DataService } from './data.service';
import { SocketService } from './socket.service';

@Component({
  selector: 'app-root',
  template: `
    Graph Data: {{ data }}
  `,
})
export class AppComponent implements OnInit, OnDestroy {

  data: any; // <-- not an Observable
  subscription: Subscription;

  constructor (
    private dataService: DataService,
    private socketService: SocketService,
  ) {}

  ngOnInit() {
    // Get the data from the socket service
    this.socketService.sendQuery();

    this.subscription = this.dataService.getGraphData().subscribe(graphData => {
      // set the value in the viewmodel with the data from the service
      this.data = graphData.text;
    });
  }

  ngOnDestroy(): void {
    this.subscription.unsubscribe();
  }

}

首先,安装依赖项,然后使用:ng serve运行示例代码,您将看到从服务回显的值。