Search code examples
angulardomangular2-services

Angular 2 sending object from one component to other


I'm new to programming and angular2.. Here I'm trying to send object from one component to other on click event using service but i'm not getting any data..

this is parent component...

import { Component } from '@angular/core';
import {Http, Headers,Response } from '@angular/http';
import {Observable} from 'rxjs/Rx';
import 'rxjs/add/operator/map';
import {SelectedItemService} from './selecteditem.service'

@Component({
    selector: 'newcomponent',
    providers:[SelectedItemService],
    template:`<p>

    </p>
    <h2>Your Title: {{nameValue}}</h2>
    <ul><li *ngFor="let list of lists">Hello {{ list }}</li></ul> 
    <form class="ui large form segment"> 
    <h3>Add a Link</h3> <div> 
     <label for="title">Title:</label>  
      <input [(ngModel)]="nameValue" placeholder="title" name="Title" >
      </div>   
      <label for="link">Link:</label>  <input name="link"></form>
      <div class=container *ngFor="let data of dataServer"
      [class.selected]="data === selectedItem"
       (click)="onSelect(data)"> 

         <div id="myimages">
         <a routerLink="/SecondNewCom">
         <img src="my_base_url/{{data.images.image3}}">
         </a>
   <router-outlet></router-outlet>
         </div>
<div class=caption>       {{data.productName}} </div></div>`,
    styleUrls: [`./app/mydoc.css`]



})
export class NewComponent {
    nameValue: string;
    lists: string[];
    url:string;
    dataServer:JSON[];
    length:number;
    selectedItem:JSON;


    constructor(private http:Http, public myservice:SelectedItemService) {
        this.myservice=myservice;
        this.nameValue = "declaredName";
        this.url="my_base_url";
        this.lists = ['abc', 'xyz', 'lol'];
this.http.get(this.url).map((res:Response) => res.json())
      .subscribe(
        data => { this.dataServer = data
            this.length=Object.keys(this.dataServer).length},
        err => console.error(err),
        () => console.log('done')
      );}

      onSelect(data:JSON):void{
            this.selectedItem=data;
            this.myservice.selectedItem=data;

      }
}

this is child component...

import {Component,Input} from '@angular/core';
import {SelectedItemService} from './selecteditem.service'
@Component({
    selector:'secondcomponent',
    providers:[SelectedItemService],
    template:`<h1> This is second new Component</h1>
    {{UiSelectedItem}}


   `

})
export class SecondComponent{
     UiSelectedItem:JSON;
     constructor(public mservice:SelectedItemService) {
        this.mservice=mservice;
        this.UiSelectedItem=mservice.selectedItem;

     }

}

this is service.ts..

import { Injectable } from '@angular/core';

    @Injectable()
    export class SelectedItemService {
        selectedItem:JSON;
    }

Also I'm not sure if I'm doing it right please suggest...


Solution

  • Don't add SelectedItemService to providers of the component. This way every component will get it's own instance. Add it to providers of NgModule instead, then you'll have a single instance for the whole application.