create src/app/employee-service.service.spec.ts
create src/app/employee-service.service.ts
2. 在service裡面寫 getEmployees() function
/* employee-service.service.ts*/
----------------------------------------------
import { Injectable } from '@angular/core';
@Injectable()
export class EmployeeService {
employessData = [
{"id":1, "name":"name_1", "age":11},
{"id":2, "name":"name_2", "age":12},
{"id":3, "name":"name_3", "age":13}
];
// getEmployees() in service
getEmployees(){
return this.employessData;
}
constructor() { }
}
3. import service
/* app.component.ts*/
----------------------------------------------
import { Component } from '@angular/core';
import { EmployeeService } from "./employee.service" //import service
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: [EmployeeService] // add providers
})
export class AppComponent {
title = 'app works!';
}
/* employee-list.component.ts*/
----------------------------------------------
import { Component, OnInit } from '@angular/core';
import { EmployeeService } from '../employee.service'; //import service
@Component({
selector: 'app-employee-list',
templateUrl: './employee-list.component.html',
styleUrls: ['./employee-list.component.css']
})
export class EmployeeListComponent implements OnInit {
employees = [];
constructor(private _empService: EmployeeService) { }
ngOnInit() {
this.employees = this._empService.getEmployees();//get data via emp service
}
}
/* employee-list.component.html*/
----------------------------------------------
result:
沒有留言:
張貼留言