Transfer data from one components to another using service (Angular)
Service
import { Injectable } from '@angular/core';
@Injectable() export class DataService { name=''; constructor() { } setMessage(message: string) { name:message } }
Now most important part is to register service in Providers inside app.module. if you will declare it in every component instead of app.module then it will create new object every time and you will loss your stored value.
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { AddComponent } from './add/add.component';
import { HomeComponent } from './home/home.component';
import { EditComponent } from './edit/edit.component';
import {DataService} from './emp.service'
@NgModule({
declarations: [
AppComponent,
AddComponent,
HomeComponent,
EditComponent
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule
],
providers: [DataService ], //Register service here then don't register it in
//every component.
bootstrap: [AppComponent]
})
export class AppModule { }
To set Message:-
this.service.setMessage("Hello from Sibling")
To read value from another component:- name = this.service.name
Comments
Post a Comment