0

SERVICE--

import {Injectable} from '@angular/core';
import {UserData} from '../user-data/user-data.component';

@Injectable()
export class UserDataService {

    constructor(){}
    userdata:UserData[]; 

    getData(){
        console.log('service',this.userdata);
        return this.userdata;
    }

    setData(user:any){
        this.userdata=user;
        console.log(this.userdata);
    }
}

USER-DATA-class ---

export class UserData {
    firstname: string;
    middlename: string;
    lastname: string;
    email: string;
    contact: number;
}

Component1 --

import { Component,OnInit,OnDestroy } from '@angular/core';
import { UserData } from '../../user-data/user-data.component';
import { ViewEditUser } from '../../view-edit-user/view-edit-user.component';
import {UserDataService} from '../../user-data-service/user-data-service.service';

@Component({
    selector: 'form-page',
    templateUrl: `app/add-user-sidebar/user-form/form.component.html`,
    providers:[UserDataService]
})

export class Form implements OnInit,OnDestroy {

    userdetail:UserData;
    constructor(private service:UserDataService){
    }

    addUser(first:string,middle:string,last:string,emailid:string,contactno:number){
        this.userdetail=({firstname:first,middlename:middle,lastname:last,email:emailid,contact:contactno})
        console.log(this.userdetail);
        this.service.setData(this.userdetail);  
    }

    ngOnInit(){
    }

    ngOnDestroy(){
    }
}

Component2--

import { Component,Input, OnInit } from '@angular/core';
import { Form } from '../add-user-sidebar/user-form/form.component';
import {UserData} from '../user-data/user-data.component';
import { WelcomePage } from '../welcome-page/welcome-page.component';
import {UserDataService} from '../user-data-service/user-data-service.service';

@Component({
    selector:'view-edit',
    templateUrl: 'app/view-edit-user/view-edit-user.component.html',
    providers: [UserDataService]
})  

export class ViewEditUser implements OnInit {
  arraydata:any;
    constructor(private service:UserDataService){}

  // arraydata:any;
   printarray(){
       console.log(this.arraydata);
   }
    ngOnInit()
    {
        this.arraydata=this.service.getData();
        console.log("hhghdfghdf",this.arraydata);    
    }

}

I am new to angular2, I have two components in my module, one component is a form where user inputs data, that data is then sent to a service, when I console.log it then I can see the data in service. but when I try to access that array from the second component then I can't access the data what to do?

adiga
  • 28,937
  • 7
  • 45
  • 66
  • Check this -> http://jasonwatmore.com/post/2016/12/01/angular-2-communicating-between-components-with-observable-subject – Bogdan Bogdanov Aug 31 '17 at 11:53
  • You can hold the value in service and try to access the value from service – Vignesh Aug 31 '17 at 12:11
  • You can see an **implementation here in this answer**: https://stackoverflow.com/a/45833455/2900305 In that particular situation the question is about _Number_ type, but the same applies for objects as well. – Igor Dimchevski Aug 31 '17 at 12:54

2 Answers2

1

If you provide the service on each component, you can't use it for communication, because each component will get a different service instance.

If one component is a parent (ancestor) of the other component, only provide it on the parent component. Otherwise provide it on a component that is a parent (anjestor) of both or provide it only in @NgModule() to make the service global.

You also need to be aware that it's possible that one component reads, before the other set the value, depending on where you set the value and in what order the components are created. Using a BehaviorSubject usually avoids this pitfall, because this way it doesn't matter which component is created first or if one component tries to read, while the other hasn't set the value yet.

For shareing between to Angular instances see also How to share service between two modules - @NgModule in angular2?

Günter Zöchbauer
  • 490,478
  • 163
  • 1,733
  • 1,404
  • 1
    this answer describes in detail about sharing data between component using service in a module. more details can be found at https://stackoverflow.com/questions/40089316/how-to-share-service-between-two-modules-ngmodule-in-angular2 – Aniruddha Das Sep 01 '17 at 07:15
  • 1
    This answer is about communication between 2 different Angular applications on the same page. Thanks for finding it anyway, was just looking for it recently and couldn't find it. – Günter Zöchbauer Sep 01 '17 at 07:22
0

You nee to use observables to pass data between components.

In your service create a Subject type variable and in the your first component do a .next to pass data to the service and in your 2nd component, subscribe to the service veriable and it will get you the data.

You are not getting the data because of the async behavior of JavaScript which will be handled by observables

Aniruddha Das
  • 14,517
  • 13
  • 83
  • 111