在两个 angular 2 个组件打字稿文件之间传递值

Passing value between two angular 2 component typescript files

我有两个不是父组件的组件,它们是子组件,但我需要将数据从组件 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

如果他们没有 parent/child 关系,最好的方法是共享服务 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.

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

时调用