资讯专栏INFORMATION COLUMN

angular2初入眼帘之-service

jokester / 2018人阅读

摘要:前集回顾上一章里我们在里通过组合三个组件,并通过单向数据流的方式把她们驱动起来。设计每章都会提一下,先设计使用场景这种方式,我们称之为,不了解的朋友参考以手写依赖注入。

前集回顾

上一章里我们在AppComponent里通过组合InputItemCheckableItemCounter三个组件,并通过Unidirectional Data Flow(单向数据流)的方式把她们驱动起来。今天这章,我们讲讲angular2里的service

本章源码:service

本章使用angular2版本为:2.4.5webpack版本为: 2.2.0

先来看看我们将要完成的效果图:

需求分析

(注意动画部分),在上一章的基础上我们加入了初始化数据,在数据加载完成前会有一个loading,数据准备好之后loading消失,列表显现。

设计use case

每章都会提一下,先设计使用场景(这种方式,我们称之为"BDD",不了解的朋友参考以BDD手写依赖注入(dependency injection))。

重构ts/app.ts
import {Component, OnInit} from "@angular/core";

import {Item} from "./CheckableItem";

//引入本章主题ItemService
import {ItemService} from "./ItemService";

@Component({
    selector: "my-app",
    template: `
    

My First Angular 2 App

Loading

`, directives: [InputItem, CheckableItem, Counter], //注入ItemService providers: [ItemService] }) export class AppComponent implements OnInit { items: Item[] = []; //声明loading状态,初始值为true loading: boolean = true; //通过构造器自动获取ItemService实例 constructor(private _itemService: ItemService) { } //在组件初始化以后调用ItemService获取初始化数据 ngOnInit() { this._itemService .getItems() .then(data => { //重置loading状态为false this.loading = false; //设置初始值 this.items = data; }); } addItem(item: Item) { this.items = [...this.items, item]; } toggle(item: Item, index: number) { this.items = [ ...this.items.slice(0, index), { isChecked: !item.isChecked, txt: item.txt }, ...this.items.slice(index + 1) ]; } }
实现ItemService
touch ts/ItemService.ts

向刚创建的ts/ItemService.ts中,添加如下内容:

import {Injectable} from "@angular/core";

import {Item} from "./CheckableItem";

//用Injectable装饰器声明该类可被依赖注入
@Injectable()
export class ItemService {

    //设置一个初始值数组
    private items: Item[] = [
        {
            isChecked: true,
            txt: "Learn JavaScript"
        }, {
            isChecked: false,
            txt: "Learn TypeScript"
        }, {
            isChecked: false,
            txt: "Learn Angular2"
        }
    ];

    //提供一个方法,返回初始数据的Promise
    getItems(): Promise> {
        return new Promise((resolve, reject) => {
            //这里手动做延迟是为了模拟网络请求
            setTimeout(() => {
                resolve(this.items);
            }, 1500);
        });
    }
}
查看效果

本章内容比较简单,写到这里差不多算结束了(其实还没有哦!),先来跑跑看

npm start

OK,我确信这个代码是可以运行的,那到底什么是service?我们现在来对着代码讲一讲。

什么是service

service是可被替换的

service必须通过依赖注入使用

service通常用作数据存取等应用中可公用逻辑部分

如何定义service

必须通过@Injectable装饰器声明

import {Injectable} from "@angular/core";

@Injectable()
export class ItemService {
}
使用service

引入service

import {ItemService} from "./ItemService";

切忌不要自作多情的new她哦!!!!!

构造器获取实例

constructor(private _itemService: ItemService) { }

自动注入实例

就像directives那样,添加到@Component的metadata中

providers: [ItemService]

就这么简单,so easy 有木有?

重构

那么我们说,到这里就结束了吗?请看下面,template里有这么一段:

用了*ngForitems列表化

用了*ngIf控制loading的显示状态

是不是感觉有点儿矬了,如果能有个多带带的ItemList组件该多好?像这样使用:

import {Component, OnInit} from "@angular/core";

import {Item} from "./CheckableItem";

import {ItemService} from "./ItemService";

@Component({
    selector: "my-app",
    template: `
    

My First Angular 2 App

`, providers: [ItemService] }) export class AppComponent implements OnInit { items: Item[] = []; loading: boolean = true; constructor(private _itemService: ItemService) { } ngOnInit() { this._itemService .getItems() .then(data => { this.loading = false; this.items = data; }); } addItem(item: Item) { this.items = [...this.items, item]; } toggle(e: { item: Item, index: number }) { this.items = [ ...this.items.slice(0, e.index), { isChecked: !e.item.isChecked, txt: e.item.txt }, ...this.items.slice(e.index + 1) ]; } }
实现ItemList
touch ts/ItemList.ts

向刚创建的ts/ItemList.ts中,添加如下内容:

import {Component, Input, Output, EventEmitter, ChangeDetectionStrategy} from "@angular/core";

import { Item } from "./CheckableItem";

@Component({
    changeDetection: ChangeDetectionStrategy.OnPush,
    selector: "item-list",
    template: `
    
    
    

Loading

` }) export class ItemList { @Input() data: Item[]; @Input() showLoading: boolean; @Output() onItemClicked = new EventEmitter(); clickItem(e: Item, i: number) { this.onItemClicked.emit({ item: e, index: i }); } }

一切都结束了,效果仍然没有变,还是很屌的样子!!!!

下回预告:使用Routing

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/79263.html

相关文章

  • angular2初入眼帘-多components协作

    摘要:我们使用了模式书写,并引入了思想,这些以前只在里见到的设计,现在里也有体现,并且在本章中会着重讲解多的协作。如果之前写过,那对于这种书写方式一定无比熟悉。每次数据的变更,无论是还是,都将变化冒泡到,然后由再向下逐级推送各组件是否重绘。 前集回顾 在上一章里我们讲了如何在angular2下开发一个component(还没做的赶紧去学吧)。我们使用了Unidirectional Data ...

    dreamans 评论0 收藏0
  • angular2初入眼帘-搭个环境

    angular2是什么?我猜不容我赘述,各位一定略有耳闻,无论是曾经AngularJS的拥趸,亦或是React的粉丝,都或多或少的对她有过一点了解。未见其物、先闻其声,angular2在问世之前已经做足了宣传,想必诸位也一定被下面各种词汇所震慑,什么:TypeScript、 ES5、 ES6、 Dart、 Immutable、 Unidirectional Data Flow、 Reactive ...

    everfight 评论0 收藏0
  • angular2初入眼帘-了解component

    摘要:通过增加删除元素改变布局的。譬如和控制元素显示隐藏,或者改变元素行为的。譬如设计看过我之前介绍以手写依赖注入的朋友应该已经对行为驱动多少有些了解了。她有,并且包含了至少一个和一个标签。,将左边的事件传递给了右边的表达式通常就是事件处理函数。 前集回顾 在上一章里我们讲了如何为angular2搭建开发环境(还没搭起来的赶紧去看哦),并使之跑起来我们的第一个My First Angular...

    ixlei 评论0 收藏0
  • Angular2 Dependency Injection

    摘要:前言依赖注入是的核心概念之一。会帮我们管理并且维护这些依赖关系。在组件当中我们没有看到任何操作符,但是程序启动后我们可以看到控制台打印了。 前言 依赖注入是Angular的核心概念之一。通过依赖注入,我们可以将复杂、繁琐的对象管理工作交给Angular,将我们的工作重心更好的放在业务上。依赖注入本身是后端编码的概念,熟悉Spring框架的对其应该不陌生,Angular1首次将依赖注入引...

    yhaolpz 评论0 收藏0
  • angular1.x和angular2+并行,angular1.x 升级 angular2+方案

    摘要:可以在不必打断其它业务的前提下,升级应用程序,因为这项工作可以多人协作完成,在一段时间内逐渐铺开,下面就方案展开说明主要依赖提供模块。在混合式应用中,我们同时运行了两个版本的。这意味着我们至少需要和各提供一个模块。 angular1.x 升级 angular2+ 方案 我给大家提供的是angular1.x和angular5并行,增量式升级方案,这样大家可以循序渐进升级自己的应用,不想看...

    Olivia 评论0 收藏0

发表评论

0条评论

jokester

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<