【问题标题】:Passing value between two angular 2 component typescript files在两个 Angular 2 组件打字稿文件之间传递值
【发布时间】:2017-07-26 18:10:09
【问题描述】:

我有两个不是父组件的组件,它们是子组件,但我需要将数据从组件 A 传递到组件 B。 例子: 组件 A.ts 有一个数据数组 示例:

my data [
   {'name':'some a','email':'some a@gmail.com','grades':{}},
   {'name':'some b','email':'some b@gmail.com','grades':{}}
  ]

需要将我的数据传递给组件 B.ts

【问题讨论】:

    标签: javascript angular typescript angular2-template angular2-services


    【解决方案1】:

    如果他们没有父/子关系,最好的方法是共享服务injected进入A和B的构造函数。

    组件 A:

    constructor(private sharingService: SharingService) { }
    
    public myArray = [];
    
    func() {
        ...
        this.sharingService.save(this.myArray);
    }
    

    服务:

    import { Injectable, } from '@angular/core';
    
    @Injectable()
    constructor() {}
    
    private array = [];
    
    save(array) {
        this.array = array;
    }
    
    fetch() {
        return this.array;
    }
    

    组件 B:

    constructor(private sharingService: SharingService) { }
    
    public yourArray = this.sharingService.fetch();
    

    There's a good tutorial on services and component interaction on the Angular site.

    【讨论】:

    • 我可以将数据发送到 save 方法,但该数据没有进入 fetch 方法,它显示为未定义。
    • 你能添加你正在使用的代码吗(或者更好的是,一个 plunkr)?
    • 我已经根据@Sasha 的一些建议更新了我的答案
    【解决方案2】:

    我同意@Lying Cake 的回答。您应该使用该服务以便在两个独立组件之间共享数据。 您面临的 undefined 问题是因为您在构造函数中调用了 fetch 方法。而且您还没有在这里定义数组值:private array。所以,它给出了未定义的。要么定义初始值,要么从构造函数中移除 fetch 方法,仅在数组值不是undefined 时调用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-20
      • 2018-02-22
      • 2016-04-29
      • 1970-01-01
      • 2017-01-12
      • 2017-08-12
      • 2020-10-10
      相关资源
      最近更新 更多