【问题标题】:Pass the data from Component to Component [duplicate]将数据从组件传递到组件[重复]
【发布时间】:2019-12-26 18:00:20
【问题描述】:

我正在尝试将查询参数从 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 有什么顺序吗?因为在调试时,当getPrjNum 函数调用来自ReportingFilterComponent 时,我没有看到ngOnInit 被执行。我怎样才能让它工作?

【问题讨论】:

  • repProjectNumber 使用 observable。
  • 阅读this,你会找到你想要的。
  • 您可以使用:ViewChild 指令,您可以使用具有可观察对象的服务,您可以在其中放置数据并在组件中检索它,您可以使用输入指令。有很多方法,这取决于你的结构和你的需求

标签: javascript angular typescript angular7


【解决方案1】:

在组件之间传递数据不能这样工作,因为每次创建组件实例时,它的数据都会重新启动。尝试使用服务。示例:

第一个组件:

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/的示例

【讨论】:

  • 我尝试在两者之间使用服务,但显示了同样的问题undefined
  • 也分享服务代码
  • 我也添加了一个示例。
  • 这里我正在获取组件中的数据,因为我是从 URL 获取的
  • 在您的问题中添加您的服务代码,以便我获得完整的图片。
猜你喜欢
  • 2019-01-29
  • 2021-11-14
  • 2017-09-10
  • 2019-02-27
  • 2017-04-20
  • 2016-11-22
  • 2011-08-23
相关资源
最近更新 更多