在Angular中, 有時須要不同component中處理相同工作(例如getUserByID()), 通常都會將method 抽離到另一個method獨立執行. 而在Angular中 稱為service. 本質就是一個Injectable 的class. 它可以在不同component 中的constructor 中建立而不用去new 它出來.
在之前的例子中, 建立了一個folder /app/user, 內裡放著class 及service.
export class User { firstName: string; lastName: string; }
import { Injectable } from '@angular/core'; import { User } from './user'; @Injectable() export class UserService { public getAllUsers(): Promise<User> { let user: User = new User(); user.firstName = 'John'; user.lastName = 'Doe'; return Promise.resolve(user); } }
在service中, 須要加入@Injectable來介定該class須要Dependency Injection (DI); 而加入Promise<>則是使該method aync load.
import { Component } from '@angular/core'; import { UserService } from '../User/user.service'; @Component({ moduleId: module.id, selector: 'layout', templateUrl: '/app/theme/layout.component.html', providers: [UserService] }) export class LayoutComponent { Name: string; constructor(private userService: UserService) { this.setUsers(); } setUsers(): any { this.userService.getAllUsers().then(user => this.Name = user.firstName + ',' + user.lastName); return true; } }
須要留意是, 於component中須要加入provider中和於constructor 中加入.
Leave a Reply