2017-01-20 7 views
2

2つのコンポーネント間でデータを渡そうとしていますが、問題があります。新しいコンポーネント(ページ)が読み込まれると、私は自分のサービスに渡されたデータを失います。 -角度2のページ間でデータを移動する

// search.component.ts 
import {Component, Input, OnInit} from '@angular/core'; 
import {Router}      from "@angular/router"; 
import {SearchService}    from "./search.service.ts"; 
import {StoreDataService}   from "./store-data.service.ts"; 

@Component({ 
    selector: 'search', 
    templateUrl: 'search.component.html', 
    providers: [ SearchService, StoreDataService ] 
}) 
export class SearchComponent implements OnInit { 

    resDisplay: [{ id: number, name: string, books: string[] }] = []; 

    constructor(private searchService: SearchService, 
       private storeDataService: StoreDataService) { } 

    ngOnInit() { 
     this.searchService.getResults(searchValue) 
      .subscribe(res => { this.resDisplay = res; }); 
    } 

    clickRes(id:number) { 
     let choice = this.resData.filter(res => res === id); 
     this.storeDataService.storedData = choice[0]; 
     this.router.navigate(['detail-page']; 
    } 
} 

-

// page-detail.component.ts 
import {Component, Input, OnInit} from '@angular/core' 
import {ActivatedRoute} from '@angular/router' 
import {StoreDataService} from "../../core/store-data/store-data.service"; 

@Component({ 
    selector: 'detail-page', 
    templateUrl: 'detail.component.html', 
    providers: [ DetailSearchService, StoreDataService ] 
}) 
export class PageDetailComponent implements OnInit { 
    detils: MoreDetails; 

    constructor(private detailSearchService: DetailSearchService, 
       private storeDataService: StoreDataService) { 
    } 

    ngOnInit() { 
     console.log(this.storeDataService.storedData); 

     /* do stuff utilizing the storedData 
     * and get more infor from the detailSearchService. 
     */ 
    } 
} 

私はstoredDataがSearchPageから値を受信見ることができます

// store-data.service.ts 
import {Injectable} from "@angular/core"; 
@Injectable() 
export class StoreDataService { 
    private storedData: any; 
} 

:ここで私が持っているものです。しかし、私がDetailPageで吐き出すと、それは未定義です。

また、Observablesを使用してStoreDataServiceを実装しようとしましたが、detailPageと同じ結果が得られました。

私は間違っているか紛失していますか?

+0

注:スペルミスは重要ではありません。私がもう少し時間を取ると、私は大胆な例を提供しようとします。 – Machtyn

+0

'private storedData:any;'はスペルミスですか、あなたの本当のコードですか? Typescriptはプライベートプロパティ –

+0

に書き込むときにエラーをスローする必要があります。両方のコンポーネントがStoreDataServiceの異なるインスタンスに注入されるため、storedData変数にデータが永続化されません。 –

答えて

2

あなたは@Component内でサービスを提供する場合、サービスが新しいインスタンスを持つことになります

@Component({ 
    selector: 'search', 
    templateUrl: 'search.component.html', 
    providers: [ SearchService, StoreDataService ]<-- new instance 
}) 

。同じモジュール内にあるコンポーネント間でこのサービスのシングルトンインスタンスを作成する場合は、モジュール内で定義します(@NgModule)。それらが同じモジュールにない場合は、共有モジュールを作成し、そこに定義します。

関連する問題