Angular2 :Sending data from a component to a component via service

时间:2016-04-04 17:21:55

标签: typescript angular angular2-routing angular2-directives angular2-services

i'm catching a data from a component and i'm trying to send it to another component via a service

Component1 (Start) : radio box View

                <md-radio-button
                    *ngIf="item.id===1"
                    value="{{item.value}}"
                    class="{{item.class}}"
                    checked="{{item.checked}}"
                    (click)="onSelectType1(item)"> //here i'm catching the value
                {{item.label}}
            </md-radio-button>

ts code

public  onSelectType1(selected:any){
        this.formeService.type1Change(selected.nb)
}

SERVICE :

@Injectable()
export class FormeService{
public type1S : any;

public  type1Change(selected):any

{

    this.type1S=selected;  //here i'm catching it into the service

 }

Component 2 : (End) : Simple View

ts code

export class ContentComponent{

constructor(public BackService : BackgroundService ,
                public formeService: FormeService)
    {
        console.log(this.formeService.type1S) 



////// that diplays me in the console that it's undefined !!!!!!!!!!!!!!!!! 


The probleme is HERE : how may i access to the value of my variable in this part 



}

!!!!!!!! and in the same time in the view it displays me the value:

{{formeService.type1S}}  // this works normally

who may tell me how can i display the value of my data in the "end component ts code" ?????

1 个答案:

答案 0 :(得分:2)

A full example Plunker

import {Injectable, Component, Directive} from 'angular2/core'
import { BehaviorSubject } from 'rxjs/subject/BehaviorSubject';
import 'rxjs/Rx';

@Injectable()
export class FormeService {
  public type1S$:BehaviorSubject<number> = new BehaviorSubject<number>(null);

  // when new values are set notify subscribers
  set type1S(value:number) {
    this.type1S$.next(value);  
  }
}

@Component({
  selector: 'content-comp',
  template: `
<div>{{value}}</div>
`})
export class ContentComponent {
  value:number;

  constructor(public formeService: FormeService) {
    // subscribe to updates
    this.formeService.type1S$.subscribe(val => {
      this.value = val;
    });
  }
} 

@Component({
  selector: 'other-comp',
  template: `
<button (click)="clickHandler()">count</button>
`})
export class OtherComponent {
  counter:number = 0;
  constructor(private formeService: FormeService) {}

  // set new values      
  clickHandler() {
    this.formeService.type1S = this.counter++;
  }
} 

@Component({
  selector: 'my-app',
  providers: [FormeService],
  directives: [ContentComponent, OtherComponent]
  template: `
  <h2>Hello {{name}}</h2>
  <content-comp></content-comp>
  <other-comp></other-comp>
`
})
export class App {

}