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(鏈接在我的答案的頂部)嗎?內容組件顯示更新的值。 –