• Angular2快速入门-4.创建一个服务(创建NewsService提供数据)


    上篇我们使用的数据是通过mock-news.ts中的const News[] 数组直接赋给Component 组件的,这篇我们把提供数据的部分单独封装成服务

    第一、创建news.service.ts

    import { Injectable } from "@angular/core";
    import { News } from './news';
    import { NewList } from './mock-news';
    
    @Injectable()
    export class NewsService {
        getNews() {
            return Promise.resolve(NewList) ;
        }
    }
    

     装饰器@Injectable()代表该服务会在程序启动时候自动注入Component的组件中,后面会讲解怎么注入。

       我们在类NewsService中增加了一个方法 getNews方法,该方法返回一个Promise 承诺,它是一种异步技术,防止页面请求的时候线程阻塞,你可以把它理解成,当有数据的时候,会自动推送给你,

    第二、修改newslist.component

    import { Component, OnInit } from '@angular/core';
    import { News } from './news';
    import { NewList } from './mock-news';
    import { NewsService } from './news.service';
    
    @Component({
        selector:'news',
        templateUrl:'./newslist.component.html',
        styleUrls:['./newslist.component.css'],
        providers: [NewsService]
    })
    
    export class NewsListComponent implements OnInit {
      
        newlist:News[];
        selectedNew:News;
        onSelected(n:News):void{
            this.selectedNew=n;         
        }
    
        constructor(private newsService:NewsService){};
        getNews():void{
           this.newsService.getNews().then(newlist=>this.newlist=newlist); 
        }
    
        ngOnInit():void{
            this.getNews();
        }
    }
    

    在该类中我们做了三处修改

    1. 导入服务NewsService,通常服务都是.service.ts后缀,约定。

    2. 在providers中增加 NewsService,

    3. 集成 OnInit ,增加Angular2的初始化ngOnInit,主要目的是重新设置自己的属性newlist

    4.注意构造函数constructor,服务在这里DI进来。

    第三、总结

    命令行 npm start,程序可以work了,

    我们需要注意的几个点,

    1. 服务写好后,需要在Component中 导入到 Providers

    2. 集成OnInit的时候注意 import { OnInit } from '@angular/core';

    3. 注意Promise的写法,只有返回时Promise的对象的时候,才可以使用then 后续处理

    4. 了解箭头函数的使用

    最终程序下载  点击下载

  • 相关阅读:
    如何理解css3 -webkit-animation-fill-mode属性值为both时的使用方法
    关于对canvas.beginPath()的理解
    [cf10E]Greedy Change
    [atAGC055B]ABC Supremacy
    [loj6734]图上的游戏
    [gym102412D]The Jump from Height of Self-importance to Height of IQ Level
    [Aizu1410]Draw in Straight Lines
    [Aizu2993]Invariant Tree
    [zoj3990]Tree Equation
    [hdu6326]Monster Hunter
  • 原文地址:https://www.cnblogs.com/clc2008/p/7884151.html
Copyright © 2020-2023  润新知