使用 angular2 中的服务将数据传递给其他组件

Pass data to other component using service in angular2

我正在尝试使用服务将数据从 'first' 组件传递到 'second' 组件。但是当我尝试在 'second' 组件中检索数据时,它是未定义的。

这是我的代码。

import { Component, OnInit } from '@angular/core';
import {Router} from "@angular/router";
import { testData } from '../model/Data';
@Component({
  selector: 'app-first',
  templateUrl: './first.component.html',
  styleUrls: ['./first.component.css']
})
export class FirstComponent implements OnInit {
 public constructor(private router: Router,private mydata:testData) { 
    this.mydata={firstname:"Amit",lastname:"Kumar",Mobile:"12345"};
 }
ngOnInit() { }
} 

因为我在构造函数中设置了 'myData'。这是 'second' 组件中的代码。

import { Component, OnInit } from '@angular/core';
import {Router} from "@angular/router";
import { testData } from '../model/Data';
@Component({
  selector: 'app-second',
  templateUrl: './second.component.html',
  styleUrls: ['./second.component.css']
})
export class SecondComponent implements OnInit {
  public constructor(private mydata:testData) {
    console.log(this.mydata.firstname);
   }
  ngOnInit() {}
}

Data.ts

import { Injectable } from '@angular/core';
@Injectable()
export class testData{
    public firstname: string;
    public lastname: string;
    public Mobile:string;
    public constructor() { }
}

并更新了我的 app.module.ts 文件

@NgModule({
...
providers: [testData],
  bootstrap: [AppComponent]
})

'Second' component is not child component of 'first'.

当你做这个作业时

this.mydata={firstname:"Amit",lastname:"Kumar",Mobile:"12345"};

您没有分配服务的属性。您正在分配 mydata 字段以成为另一个对象。

我想你的意思是,

this.mydata.firstname = "Amit";
this.mydata.lastname = "Kumar";
this.mydata.Mobile = "12345";

如果你想引用整个对象,你应该像文档中那样使用 Subject

https://angular.io/docs/ts/latest/cookbook/component-communication.html

注意:这种方法在某些情况下可能仍然行不通;就像 FirstComponent 不能足够快地设置字段并且 SecondComponent 试图在之前获取它们..