2016-10-02 9 views
0

サービスを介して2つのコンポーネント間でデータを渡そうとしています。私は他のコンポーネントからのサービスを介してデータをどのように消費できるのかよくわかりません。私は、2.DataからgetData()メソッドを介してデータを取得し、それをデータ変数に保存しています。メソッド内では印刷できますが、メソッド外では印刷できません。また、最初のコンポーネントに渡しました。私のコードで何が間違っていますか?サービス経由でデータを渡すAngular2(2つのコンポーネント)

1コンポーネントファイル

import {Component, OnInit} from '@angular/core'; 
import {PassProfileDataService} from '../common/PassProfileDataService'; 

@Component({ 

    selector: "profile", 
    templateUrl: `client/components/profile/profile.component.html` 

}) 

export class ProfileComponent implements OnInit{ 
public data; 

constructor(private _sharedService: PassProfileDataService){} 

ngOnInit() { 

this.data = this._sharedService.dataStringSource) 
    } 

} 

2.コンポーネントファイル

import {Component} from '@angular/core'; 
import {PassProfileDataService} from '../common/PassProfileDataService'; 

@Component({ 

    selector: "search", 
    templateUrl: `client/components/search/search.component.html` 

}) 
export class ProfileComponent{ 

constructor(private _sharedService: PassProfileDataService){} 

this._sharedService.getData(data[0].values) 
ngOnInit() { 

    } 

} 

3 SharedService

import {Component, Injectable} from '@angular/core' 

@Injectable() 
export class PassProfileDataService { 

    public dataStringSource; 

    // Service message commands 
    getData(data: String) { 
    this.dataStringSource data; 

    }; 

} 

答えて

0

として私が知る限り、あなたの分析がサービスを共有として識別するように導く場合、アプリケーションの初期化でサービスを登録する必要があります。これにより、Angular2アプリケーション内の同じサービスインスタンスにアクセスできるようになります。実際には、あなたのapp.tsファイルに...

サービスのインスタンスを必要とする各コンポーネントで、TheNameServiceをインポートステートメントでインポートします。コンポーネントのproviders配列にTheNameServiceを挿入しないことを忘れないでください。そうしないと、そのコンポーネントにサービスの新しいインスタンスが追加されます。

これはあなたの質問を解決します。共有するデータがサービスの公開財産にある場合、あなたは設定されています。しかし、非同期メソッドを扱う複雑なサービスを扱っている場合はどうでしょうか? EventEmittersは助けに来ます。

In TheNameServiceでは、EventEmitterタイプのプロパティを宣言します。ここで、「タイプ」はイベントによって放出されるデータのタイプです。私。 TheNameServiceのコンストラクタで

public myevent$: EventEmitter<string>; 

このように持つEventEmitterを初期化するために覚えている:

this.myEvent$ = new EventEmitter(); 

およびサービスは、アプリケーション間でデータを共有する必要が毎回:

this.myEvent$.emit("This is the emitted text!"); 

がサブスクライブすることを忘れないでくださいコンポーネントをイベントに追加する...コンポーネントのプロパティ内にサブスクリプションを格納するとよいでしょう。コンポーネントがdestのときに聴いたイベントの登録を解除する必要があるからですロイヤルthis._theNameServiceがTheNameServiceはコンストラクタで依存性注入を注入され

ngOnInit() { 
    this._myEventSubscription = this._theNameService.myEvent$.subscribe((emittedString: string) => { 
     console.log(emittedString); // will log "This is the emitted text!" in the console 
    }); 
} 

private _myEventSubscription: any; // not sure about what kind of data type is returned here... 

がngOnInit方法でサービスイベント登録:第一に、あなたのコンポーネントに新しいプライベートプロパティを宣言(次のように...)

constructor(private _theNameService: TheNameService) { } 

行うには最後のもの、部品破壊の場合には、サブスクリプションの登録を解除:

ngOnDestroy() { 
    this._myEventSubscription.unsubscribe(); 
} 
+0

私は試しましたが、何かが間違っています。上のコードを使って説明することができますか? – Tony

0

は、あなたがコンポーネントを切り替えながら、データを保持しているサービスを確認します。以下は例です。

ここでは、2つのコンポーネントSenderとRecieverについて考えます。

送信者コード:このコードは、データをサービスに設定し、受信者にナビゲートします。

import { Router } from '@angular/router'; 
import { TransfereService } from './services/transfer.service'; 

export class SenderComponent implements OnInit {   
    constructor(
    private transfereService:TransfereService, 
    private router:Router) {} 

    somefunction(data){ 
    this.transfereService.setData(data); 
    this.router.navigateByUrl('/reciever');//as per router 
} 
} 

レシーバのコード:このコードは、サービスからデータを取得し、同様のデータを消去します。

import { Router } from '@angular/router'; 
import { TransfereService } from './services/transfer.service'; 

export class RecieverComponent implements OnInit { 
data = this.transfereService.getData();  
constructor(
    private transfereService:TransfereService, 
    private router:Router) { 
     if(this.data){ 
     // do whatever needed 
     } 
     else{ 
     this.router.navigateByUrl('/sender'); 
     } 
    } 
} 
関連する問題