2017-08-27 1 views
0

を使用して別のコンポーネントにデータを渡すAngular2は、私は私は私はこのように自分のアプリケーションをアーキテクチャ・しているすべてのコンポーネント</p> <p>間でコードを複製することなく、さまざまなコンポーネントの中で選択された日付を共有したい日付範囲を持っているサービス

<app-date-range /> //date range component 
<router-outlet></router-outlet> 

はまた、私は私のアプリモジュール・プロバイダーに追加したイベントサービスを作成している私の日付範囲内

@Injectable() 
export class ReportsEventService { 

public maininputrange = new Subject(); 
constructor() { } 

maininputrangeemit(data:any){ 
    this.maininputrange.next({type:"mainputrange", data:data}); 
} 

} 

コンポーネントiは、このように発行します

constructor(
    private _reportEventService:ReportsEventService 
){ } 

    dateRangeChanged(data){ 
    ...other implementations 
    this._reportEventService.maininputrangeemit(this.mainInput); 
    } 

私はinitで発行されたデータにアクセスするために別のコンポーネントを訪問します。

mainInput:any; 
    constructor(
     private _reportsEvenService:ReportsEventService 
    ) { 
    _reportsEvenService.maininputrange.subscribe(
     (data)=>{ 
     console.log("receiving values"); //called many times 
     this.mainInput = data; 
     } 
    ) 
    } 

ngOnInit() { 
    console.log("maininput value is"); 
    console.log(this.mainInput); //always undefined 

} 

私は間違っていますが、実装は可能ですか?

+0

利用代わりに 'Subject'の' BehaviourSubject'。私はredux(ngrx-store)を設定することを好むでしょう – Aravind

+0

ありがとう挙動の主題は働きます。 –

+0

ハッピーコーディング。 :) :) – Aravind

答えて

0

何が問題になったのかを知りたい場合は、ここをクリックしてください。 ReportsEventServiceにはsetterメソッドしかありませんが、値を返すgetterメソッドはありません。

@Injectable() 
 
export class ReportsEventService { 
 

 
    public maininputrange = new Subject(); 
 
    constructor() {} 
 

 
    setmaininputrangeemit(data: any) { 
 
    this.maininputrange.next({ 
 
     type: "mainputrange", 
 
     data: data 
 
    }); 
 
    } 
 

 
    getmaininputrangeemit(): Observalble <any> { 
 
    return this.maininputrange.asObservable; 
 
    } 
 

 
}

mainInput: any; 
 
constructor(
 
    private _reportsEvenService: ReportsEventService 
 
) { 
 
    _reportsEvenService.getmaininputrange.subscribe(
 
    (data) => { 
 
     console.log("receiving values"); //called many times 
 
     this.mainInput = data; 
 
    } 
 
) 
 
} 
 

 
ngOnInit() { 
 
    console.log("maininput value is"); 
 
    console.log(this.mainInput); //always undefined 
 

 
}

関連する問題