在2角两个组件(页)之间传递值 [英] Passing value between two components (pages) in Angular 2

查看:120
本文介绍了在2角两个组件(页)之间传递值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的角度2β(打字稿)。

我有两个组成部分(其实它们是两个页面太)。他们不是父母与子女的关系。

我想通过一个值第二个组成部分(页),当我点击第一个组件(页)。

链接

我知道URL参数,通过路由器的方式。但我不希望显示在链接此参数。有没有其他办法?

感谢您!


解决方案

的正规途径是建立一个注射服务和注入服务为需要数据的任何组件。由于该服务是一个单独的组件将访问相同的数据。它不应该的问题,他们是在不同的页面。 Plunker这里


  

编辑:以下示范订阅的eventEmitter上的服务组件之间的双向通信的更复杂的例子:的 Plunker


 进口{组件,注射}从'angular2 /核心//你的共享服务
//提供父组件或引导参考
@Injectable()
出口类为myService {
  sharedData:字符串=字符串从为myService
}@零件({
  选择:第1页,
  供应商:[],
  模板:`
    < D​​IV>
      < B>组件1页 - 共享的数据:; / B> {{SharedData}}
    < / DIV>
  `
  指令:[],
})
出口类第1页{
  构造函数(aService:为myService){
    this.SharedData = aService.sharedData
  }
}@零件({
  选择:第2页,
  供应商:[],
  模板:`
    < D​​IV>
      < B>组件第2页 - 共享的数据:; / B> {{SharedData}}
    < / DIV>
  `
  指令:[],
})
出口类第2页{
  构造函数(aService:为myService){
    this.SharedData = aService.sharedData
  }
}

I am using Angular 2 beta (TypeScript).

I have two components (actually they are two pages too). They are NOT parent and child relationship.

I want to pass a value to second component(page) when I click the link in the first component(page).

I know "URL parameters" way through router. But I don't want to show this parameter in the link. Is there any other way?

Thank you!

解决方案

The canonical way is to establish an injectable service and inject the service into any components that need the data. Since the service is a singleton, the components will be accessing the same data. It shouldn't matter that they are on different pages. Plunker here.

Edit: Here's a more involved example that shows two-way communication between components by subscribing to an eventEmitter on a service: Plunker

import {Component, Injectable} from 'angular2/core'

// your shared service 
// provide reference in parent component or bootstrap 
@Injectable()
export class myService {
  sharedData:string = "String from myService"
}

@Component({
  selector: 'page1',
  providers: [],
  template: `
    <div>
      <b>Component Page1 - shared data:</b> {{SharedData}}
    </div>
  `,
  directives: [],
})
export class Page1 {
  constructor(aService: myService) {
    this.SharedData = aService.sharedData
  }
}

@Component({
  selector: 'page2',
  providers: [],
  template: `
    <div>
      <b>Component Page2 - shared data:</b> {{SharedData}}
    </div>
  `,
  directives: [],
})
export class Page2 {
  constructor(aService: myService) {
    this.SharedData = aService.sharedData
  }
}

这篇关于在2角两个组件(页)之间传递值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆