Monday, June 11, 2018

Services - 01 - Custome Services

my.module.ts
------------------

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { MyComponent } from "./components/my.component";
import { MyService} from "./services/my.service"

@NgModule({
declarations: [
AppComponent,
MyComponent
],
imports: [
BrowserModule
],
providers: [MyService],
bootstrap: [MyComponent]
})
export class AppModule { }


create the folder in app in src - folder name is services

create file name - my.service.ts

my.service.ts
----------------

//import Injectable
//Injectable class used to create the custom service.
import { Injectable } from "@angular/core";

//Decorator
@Injectable()
export class MyService{
private data:any;

constructor(){
this.data = {
p_id:111,
p_name:"Product One",
p_cost:10000
};
};

public getData():any{
return this.data;
}

}

create the folder in app in src - folder name is components

create file name - my.component.ts
create file name - my.component.html


my.component.ts
---------------------


import { Component } from "@angular/core";
import { MyService} from "../services/my.service";

@Component({
selector:"cust-ser",
templateUrl:"./my.component.html"
})

export class MyComponent{
private data:any;
constructor(private _service:MyService){

}

ngOnInit(){
this.data=this._service.getData();
}
}


my.components.html
--------------------------

<h1>{{data | json}}</h1>


app.module.ts
-----------------

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { MyComponent } from "./components/my.component";
import { MyService} from "./services/my.service"

@NgModule({
declarations: [
AppComponent,
MyComponent
],
imports: [
BrowserModule
],
providers: [MyService],
bootstrap: [MyComponent]
})
export class AppModule { }



----

No comments:

Post a Comment