Angular2: Using Data Service to communicate between components in Angular2 Application

Standard

Since services in angualr2 are singleton, so this give us leverage to have same value through different modules and components, during complex application development, we come across a common scenario where we want to communicate two different modules or components by passing values between them.

Data services usually resolve our this issue, they are easy to implement, maintain and super fun to read. Solution is simple define setter/getter for particular variable in service and then import this service in multiple components to read or write value.

Bold code below shows this design guideline implementation

url-history-store.service.ts:

import { Injectable } from '@angular/core';

@Injectable()
export class UrlHistoryService {
    private urlHistory: string;

    constructor() {
        this.urlHistory = "";
    }

    public setUrlHistoryObj(val: string): void {
        this.urlHistory = val;
    }

    public getUrlHistoryObj(): string {
        return this.urlHistory;
    }

}

Producer Component:

import { Component } from '@angular/core';
import { UrlHistoryService } from '../shared/service/url-history-store.service';

@Component({
    selector: 'search-movie-list-producer',
    templateUrl: '../../Scripts/app/search-movies/search-movie-list.component.html'
})

export class SearchMovieListProducerComponent {
    constructor(
        private urlHistoryService: UrlHistoryService) {

        this.urlHistoryService.setUrlHistoryObj("/movie/searchMovie");
    }
}

Consumer Component:

import { Component } from '@angular/core';
import { UrlHistoryService } from '../shared/service/url-history-store.service';

@Component({
    selector: 'search-movie-list-b',
    templateUrl: '../../Scripts/app/search-movies/search-movie-list.component.html'
})

export class SearchMovieListConsumerComponent {
    backUrl: string;

    constructor(
        private urlHistoryService: UrlHistoryService) {

        this.backUrl = this.urlHistoryService.getUrlHistoryObj();
    }
}

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s