将数据从Component传递到Component

时间:2019-08-21 12:43:35

标签: javascript angular typescript angular7

我正在尝试将查询参数从URL导入到组件中,并且按预期方式工作,现在我想将数据从该组件中导入到另一个组件中。但是我得到undefined

我要获取查询参数的组件:

export class ProjectShipmentComponent implements OnInit {
  public repProjectNumber : string;

  constructor( private activatedRoute: ActivatedRoute) { }

   ngOnInit() {
    this.activatedRoute.params.subscribe(params => {
      this.repProjectNumber = params['reportProject'];
      console.log(this.repProjectNumber);
    })}
  getPrjNum()
  {
    return this.repProjectNumber;
  }}

现在,我正尝试将此repProjectNumber检索到另一个组件,例如

    import { ProjectShipmentComponent } from '../project-shipment.component';
    export class ReportingFilterComponent implements OnInit {
    repPrj : string;
    constructor(private psc :ProjectShipmentComponent ) {
       this.repPrj = this.psc.getPrjNum();
      console.log(this.repPrj);

我在这里不确定。 ngOnInit的执行顺序如何?因为在调试时,从ngOnInit进行getPrjNum函数调用时,我没有看到ReportingFilterComponent被执行。我该如何工作?

1 个答案:

答案 0 :(得分:0)

无法在组件之间传递数据,因为每次创建Component实例时,都会重新启动其数据。尝试使用服务。示例:

第一个组件:

import { Component, OnInit } from '@angular/core';
import { DataService } from "../data.service";

@Component({
  selector: 'app-parent',
  template: `
    {{message}}
  `,
  styleUrls: ['./sibling.component.css']
})
export class ParentComponent implements OnInit {

  message:string;

  constructor(private data: DataService) { }

  ngOnInit() {
    this.data.currentMessage.subscribe(message => this.message = message)
  }

}

第二部分:

import { Component, OnInit } from '@angular/core';
import { DataService } from "../data.service";

@Component({
  selector: 'app-sibling',
  template: `
    {{message}}
    <button (click)="newMessage()">New Message</button>
  `,
  styleUrls: ['./sibling.component.css']
})
export class SiblingComponent implements OnInit {

  message:string;

  constructor(private data: DataService) { }

  ngOnInit() {
    this.data.currentMessage.subscribe(message => this.message = message)
  }

  newMessage() {
    this.data.changeMessage("Hello from Sibling")
  }

}

服务:

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

@Injectable()
export class DataService {

  private messageSource = new BehaviorSubject('default message');
  currentMessage = this.messageSource.asObservable();

  constructor() { }

  changeMessage(message: string) {
    this.messageSource.next(message)
  }

}

来自https://angularfirebase.com/lessons/sharing-data-between-angular-components-four-methods/

的示例