angularjs2 学习笔记(三) 服务

在anglar2中服务是什么?

如果在项目中有一段代码是很多组件都要使用的,那么最好的方式就是把它做成服务。

服务是一种在组件中共享功能的机制,当我们使用标签将多个组件组合在一起时我们需要操作一些数据或是需要做一些运算时,我们需要做一个服务;服务能帮我们引入外部的数据。那么如何创建一个服务呢?

创建服务

创建一个简单的服务

import {Injectable} from 'angular2/core';

import {PLANETS} from './planets-data';

 

@Injectable()

export class PlanetService {

    getPlanets(){

        return Promise.resolve(PLANETS);

    }

}

首先需要一个Injectable的指令,这个指令能告诉其他引用的组件这个服务是可注入的。

然后定义一个方法用来返回数据。

服务调用

服务调用也很简单

import {Component} from "angular2/core";

import {PlanetService} from "./planet.service"; //1

import {PlanetComponent} from "./planet.component";

import {Planet} from "./planet";

 

 

@Component({

    selector: "my-app",

    templateUrl: "app/planet-list.component.html",

    directives: [PlanetComponent],

    providers:[PlanetService], //2

    styles:[`

                body{

                    padding:0;

                    margin:0;

                    font-family:Roboto,Arial,sans-serif;

                    font-size:16px

                }

                .title {

                    color:#018EFA;

                }

                .clicked{

                    background-color: #9C00FE;

                    color:white;

                }

                .labels{

                    background-color: black;

                    color: white;

                }

 

    `]

})

export class PlanetListComponent{

    public planets : Planet[];

 

    public selectedPlanet = {};

 

    public onNameClick(planet){

        this.selectedPlanet = planet;

    }

    constructor(private _planetService: PlanetService){  // 3

        this.getPlanets();

    }

 

    // make a call to our planet service

    getPlanets(){  //4

        this._planetService.getPlanets().then((planets:Planet[])=>this.planets = planets);

    }

 

}

1、  引入服务(import)

2、  使用providers 来注入服务

3、  创建一个服务的示例

使用promise调用服务

原文地址:https://www.cnblogs.com/oldkingsir/p/5533669.html