[Angular] 建立 Service

在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 中加入.

 

About C.H. Ling 260 Articles
a .net / Java developer from Hong Kong and currently located in United Kingdom. Thanks for Google because it solve many technical problems so I build this blog as return. Besides coding and trying advance technology, hiking and traveling is other favorite to me, so I will write down something what I see and what I feel during it. Happy reading!!!

Be the first to comment

Leave a Reply

Your email address will not be published.


*


This site uses Akismet to reduce spam. Learn how your comment data is processed.