Angular 2将对象从一个组件发送到另一个组件

时间:2016-10-05 14:51:49

标签: angular dom angular2-services

我是编程和angular2的新手。在这里,我尝试使用服务在点击事件中将对象从一个组件发送到另一个组件,但我没有得到任何数据..

这是父组件......

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;

      }
}

这是儿童成分......

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;

     }

}

这是service.ts ..

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

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

此外,我不确定我是否正确行事请建议......

1 个答案:

答案 0 :(得分:1)

不要将SelectedItemService添加到组件的提供者。这样每个组件都将获得它自己的实例。将其添加到NgModule的提供商,然后您将为整个应用程序提供单个实例。