Chapter2 Services in angular4
app.component.html
1 2 3 4 5 6 7 8 9 10 11 |
<!--The whole content below can be removed with the new code.--> <div style="text-align:center"> <h1> Welcome to {{title}}!! </h1> </div> <ul> <li *ngFor="let address of addresses">{{ address }}</li></ul> <p>{{ someString }}</p> |
app.component.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
import { Component, OnInit } from '@angular/core'; import { StudentDataService } from './student-data.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], providers: [StudentDataService] }) export class AppComponent implements OnInit { title = 'app'; name: string; addresses: string[]; someString= ''; // for service demo ngOnInit(): void { this.name = 'SHiv'; this.addresses = ['chopda', 'pune']; console.log(this.dataService.skills); this.someString = this.dataService.myData(); } constructor(private dataService: StudentDataService) { } } |
app.module.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { AppComponent } from './app.component'; import { FormComponent } from './form/form.component'; import { Router, RouterModule } from '@angular/router'; @NgModule({ declarations: [ AppComponent, FormComponent ], imports: [ BrowserModule, FormsModule, RouterModule.forRoot([ { path: 'form', component: FormComponent } ]) ], providers: [], bootstrap: [AppComponent], }) export class AppModule { } |
Generate component
type in terminal
1 |
ng g service studentdata |
student-data.service.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import { Injectable } from '@angular/core'; @Injectable() export class StudentDataService { skills= [ 'java', 'javascript' ]; constructor() { } // service related method myData() {return 'skills generated'; } } |