1

我现在是组件捕获数据,我想通过服务Angular2:通过服务

的Component1(开始)将它发送到另一个组件从组件将数据发送到一个组件:无线电箱 查看

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

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 

} 

组分2:(完):简单查看

TS码

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 



} 

!!!!!!! !并在视图中的同一时间,它显示我的价值:

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

谁可以告诉我,我怎样才能在“结束组件TS码”显示我的数据的价值?????

+0

如果你不认为这是一个重复添加评论,把它重新打开。 –

+0

问题是如何重新使用我的数据在ts代码中的值不在视图中,使用主体可以传递数据并将其显示在视图中但这里的上下文是如何从代码的一部分显示它 – firasKoubaa

+0

部分使用'.subscribe('将在TypeScript中获得服务中值的更改通知。 –

回答

2

完整的例子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 { 

} 
+0

谢谢很多的答案和宝贵的帮助,但我不知道是否问题仍然存在,请注意,如果我想在内容组件中显示“valu”的值,它将显示null(第一个值)即使经过2或3次点击后 – firasKoubaa

+0

console.log(this.value); //总是(内部内容组件) – firasKoubaa

+0

你检查了Plunker(链接在我的答案的顶部)吗?内容组件显示更新的值。 –