Machtyn
Machtyn

Reputation: 3272

moving data between pages in angular 2

I'm trying to pass data between two components, but I'm having some issue with it. When the new component (page) loads, I lose the data I passed into my service. Here's what I've got:

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

-

// 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. 
        */
    }
}

I can see the storedData receiving the value from the SearchPage. But when I try to spit it out on the DetailPage, it is undefined.

I also tried implementing the StoreDataService using Observables, with the same result on the detailPage.

What am I doing wrong or missing?

Upvotes: 2

Views: 1151

Answers (1)

eko
eko

Reputation: 40647

If you provide the service inside the @Component,

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

That service will have a new instance. If you want to have a singleton instance of this service among your components that are in the same module, define it inside the module (@NgModule). If they are not in the same module then create a shared module and define it there.

Upvotes: 2

Related Questions