WEB DEVELOPER SITE
PYTHONJAVAPHP7
 

Angular 4 Service


Angular 4 service can be used to data connection that needs to be shared across components, etc.


To create a service
C:\projectA4\Angular 4-app>ng g service myservice
installing service
   create src\app\myservice.service.spec.ts
   create src\app\myservice.service.ts
   WARNING Service is generated but not provided, it must be provided to be used

   C:\projectA4\Angular 4-app>

we can created myservice.service.specs.ts and myservice.service.ts.

myservice.service.ts
import { Injectable } from '@angular/core';

@Injectable()
export class MyserviceService {
   constructor() { }
}
@Injectable method and a class called MyserviceService

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouterModule} from '@angular/router';
import { AppComponent } from './app.component';

import { MyserviceService } from './myservice.service';
import { NewCmpComponent } from './new-cmp/new-cmp.component';
import { ChangeTextDirective } from './change-text.directive';
import { SqrtPipe } from './app.sqrt';

@NgModule({
   declarations: [
      SqrtPipe,
      AppComponent,
      NewCmpComponent,
      ChangeTextDirective
   ],
   imports: [
      BrowserModule,
      RouterModule.forRoot([
         {
            path: 'new-cmp',
            component: NewCmpComponent
         }
      ])
   ],
   providers: [MyserviceService],
   bootstrap: [AppComponent]
})

export class AppModule { }
We can use the same function in the main parent component app.component.ts and also in the new component new-cmp.component.ts t
import { Injectable } from '@angular/core';
@Injectable()
export class MyserviceService {
   constructor() { }
   showTodayDate() {
      let ndate = new Date();
      return ndate;
   }
}