Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

typescript - Passing value between two components (pages) in Angular 2

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...