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

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

问题描述

我使用的是 Angular 2 (TypeScript)

我有两个组件(实际上它们也是两页).他们不是父子关系.

当我点击第一个组件(页面)中的链接时,我想将一个值传递给第二个组件(页面).

我知道通过路由器的URL 参数"方式.但我不想在链接中显示这个参数.还有其他办法吗?

谢谢!

解决方案

规范的方式是建立一个 injectable 服务并将该服务注入到任何需要数据的组件中.由于服务是单例,组件将访问相同的数据.它们在不同的页面上应该无关紧要.Plunker 在这里.

<块引用>

这是一个更复杂的示例,通过订阅服务上的 eventEmitter 显示组件之间的双向通信:Plunker

import {Component, Injectable} from 'angular2/core'//你的共享服务//在父组件或引导程序中提供引用@Injectable()导出类 myService {sharedData:string = "来自 myService 的字符串"}@成分({选择器:'page1',提供者:[],模板:`<div><b>组件页面 1 - 共享数据:</b>{{共享数据}}

`,指令:[],})导出类 Page1 {构造函数(aService:myService){this.SharedData = aService.sharedData}}@成分({选择器:'page2',提供者:[],模板:`<div><b>组件页面 2 - 共享数据:</b>{{共享数据}}

`,指令:[],})导出类 Page2 {构造函数(aService:myService){this.SharedData = aService.sharedData}}

I am using Angular 2 (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
  }
}

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

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆