Amit Kumar
Amit Kumar

Reputation: 5962

Pass data to other component using service in angular2

I'm trying to pass data from 'first' component to 'second' component using service. But When I try to retrieve data in 'second' component, It is undefined.

This is my code.

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() { }
} 

As I have set 'myData' in constructor. This is code in 'second' component.

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() { }
}

and updated my app.module.ts file

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

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

Upvotes: 2

Views: 2089

Answers (1)

eko
eko

Reputation: 40677

When you do this assignment

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

You are not assigning the properties of your service. You are assigning you mydata field to become an another object.

I think what you meant to do is,

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

If you want to refer to the whole object you should use a Subject like in the documentation:

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

Note: This approach still might not work in some cases; like if FirstComponent can't set the fields fast enough and SecondComponent tries to get them before..

Upvotes: 2

Related Questions