Angular - 从子组件到父组件的通信

时间:2018-02-01 13:14:53

标签: javascript angular typescript

我没有得到我,如何在组件和服务之间进行通信.. :( 我已阅读并尝试了很多关于即使某些例子以某种方式工作,我也不明白为什么(?)

我想要实现的目标: 我有一个父母和两个子组件:

  • 仪表板
    • 工具栏
    • 图表

在工具栏组件中我有一个搜索域,它从外部源获取结果(通过服务工作)..当结果到达时,我需要触发updateGraph() - 图形组件中的方法

toolbar.component.ts

import { Component, OnInit, Output, EventEmitter } from '@angular/core';
import { FormControl } from '@angular/forms';

import { WebsocketsService } from '../../../services/websockets/websockets.service';
import { DataService } from '../../../services/data/data.service';

@Component({
  selector: 'toolbar',
  templateUrl: './toolbar.component.html',
  styleUrls: ['./toolbar.component.scss'],
  providers: [WebsocketsService, DataService]
})
export class ToolbarComponent implements OnInit {

  @Output() newGraphData: EventEmitter<boolean> = new EventEmitter();

  searchField: FormControl;
  search: string;

  private isNewGraph = false;

  constructor(private _websocketsService: WebsocketsService, private _dataService: DataService) {
  }

  ngOnInit() {
    this.searchField = new FormControl();
    this.searchField.valueChanges
        .subscribe(term => {
          this.search = term;
        });    
  }

  private applySearch() {
    const res = this._websocketsService.sendQuery(this.search);
    this._dataService.setGraphData(res);
    this.newGraphData.emit(true);

    this.search = '';
    this.searchField.reset();
  }
}

图的component.ts

import { Component, OnInit} from '@angular/core';

import { HttpService } from '../../../services/http/http.service';
import { DataService } from '../../../services/data/data.service';

@Component({
  selector: 'graph',
  templateUrl: './graph.component.html',
  styleUrls: ['./graph.component.scss'],
  providers: [HttpService, DataService]
})
export class GraphComponent implements OnInit, AfterViewInit {

  constructor( private _httpService: HttpService, private _dataService: DataService ) {
  }

  ngOnInit() {
  }

  public renderResult() {   
     console.log( this._dataService.getGraphData() );     
  }
}

data.service.ts

import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';

@Injectable()
export class DataService {  

  private graphData: Subject<string> = new Subject<string>();

  public setGraphData(data) {
    this.graphData.next( data );
  }

  public getGraphData() {
    return this.graphData;
  }

  constructor() { }

}

我只想在searchresult写入'theDataData'之后执行'renderResult()'。请帮助我很困惑。

2 个答案:

答案 0 :(得分:0)

如果我理解,您需要组件和服务之间的通信。

[组件](提供信息)-----(通知)-----&gt; B [服务] ----(发送)----&gt; C [组件](消费信息)

这是对的吗?我们走了。

您需要在GraphComponent中创建graphData(data.service.ts)订阅。

import { Subscription } from 'rxjs/Subscription';

export class GraphComponent implements OnInit, AfterViewInit {

constructor( private _httpService: HttpService, private _dataService: DataService ) {
  }

private subscription: Subscription;

  ngOnInit() {
     this.subscription = this._dataService.getGraphData().asObservable().subscribe((data) => {
        console.log(data);
     });

  }
}

看这里帮助你。 http://jasonwatmore.com/post/2016/12/01/angular-2-communicating-between-components-with-observable-subject

答案 1 :(得分:0)

简短的回答,我认为您需要订阅getGraphData主题,类似这样的内容(不推荐):

public renderResult() {   
   this._dataService.getGraphData().subscribe(d => {
    console.log(d)
   });
}

根据RxJS的说法,不推荐使用https://medium.com/@benlesh/on-the-subject-of-subjects-in-rxjs-2b08b7198b93

更好地回答,在observable中创建service并订阅。{/ p>

data.service.ts

graphObservable = this.graphData.asObservable();

图的component.ts

public renderResult() {   
  this._dataService.graphObservable().subscribe(d => {
    console.log(d)
  });
}