【问题标题】:Angular 2 sending object from one component to otherAngular 2将对象从一个组件发送到另一个
【发布时间】:2017-09-18 17:26:30
【问题描述】:

我是编程和 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;
    }

另外我不确定我是否做得对,请建议...

【问题讨论】:

    标签: angular dom angular2-services


    【解决方案1】:

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

    【讨论】:

    • 非常感谢您抽出宝贵的时间......这偶尔会起作用......大多数时候我把它作为未定义的数据......我能够查看的 10 次中只有两次屏幕上的结果...其余时间仍然显示空白...知道为什么会发生这种情况...
    • 可能是时间问题。当您阅读mservice.selectedItem 时,它可能尚未从服务器到达。您需要使用可观察对象链接异步调用,否则您无法期望可靠的行为。好的例子见angular.io/docs/ts/latest/cookbook/component-communication.html
    • 当你说服务器你的意思是精简服务器???因为 mservice.selectedItem 不依赖于任何对数据的 api 调用...我试图将已经获取的数据传递给不同的组件。那么在这种情况下也会发生这种情况吗??
    • 所以您的http.get() 呼叫与问题无关?如果您在onSelect() 中设置服务的数据并将其复制到SecondComponent 的构造函数中,则服务将没有数据。如果您在构造函数中复制数据,然后在onSelect() 中更改数据,则与创建的副本没有任何联系。您需要再次复制该值以获取SecondComponent 中的更新值。这就是Observables 的用途。他们通知订阅者有关更改。
    • 很抱歉给您带来了困扰...终于遇到问题了,实际上我在图像标签中创建了超链接,onclick 直接转到新页面,并且在父组件中没有调用 onclick 方法,因此没有发送的对象数据:-D
    猜你喜欢
    • 2018-04-24
    • 1970-01-01
    • 2016-03-09
    • 2019-07-04
    • 2017-04-20
    • 2020-12-06
    • 2017-11-29
    • 2020-08-23
    • 1970-01-01
    相关资源
    最近更新 更多