zoukankan      html  css  js  c++  java
  • angular之Http服务

    原文

    https://www.jianshu.com/p/53e4a4bfad7d

    大纲

      1、什么是angular服务
      2、服务的类别
      3、认识angular的Http请求
      4、简单实例
      5、angular的http模块
      6、angular官网的英雄编辑器的服务代码
      7、angular代码资源

    什么是angular服务

      在Angular中,我们所说的服务是指那些能够被其它的组件或者指令调用的单一的,可共享的代码块.服务能够使我们提高代码的利用率,方便组件之间共享数据和方法,方便测试和维护。
      服务是一个广义范畴,包括:值、函数、或应用所需的特性
      几乎任何东西都可以是一个服务,典型的服务是一个类,具有专注的、明确的用途,它应该做一件特定的事情,并把它做好。
      服务无处不在。
      组件类应保持精简。组件本事不从服务器获得数据,不进行验证输入,也不直接往控制台写日志。它们把这些任务委托给服务
      组件的任务就是提供用户体验,仅此而已。它介于视图(由模板渲染)和应用逻辑(通常包括模型的某些概念)之间。设计良好的组件为数据绑定提供属性和方法,把其它琐事都委托给服务。

    服务的类别

      服务有很多类别:日志服务、数据服务、消息总线、税款计算器、应用程序配置。

    认识angular的Http请求

      angular的http是基于浏览器的“新特性” Fetch API 而产生的,Fetch API 和以前的 xmlhttprequest 主要功能是一样的,就是发请求.不同的地方是Fetch 是基于 promise 的,而且可以配合 service worker, stream, cache 之类的 "新特性"。

    简单实例

    /*
        testHttp.component.ts
        通过http的get请求获取本地数据
    */
    
    import 'rxjs/add/operator/map';
    import { Component, OnInit } from '@angular/core';
    import { Http } from '@angular/http';
    @Component({
      selector: 'test-http',
      templateUrl: './testHttp.component.html',
    })
    export class TestHttpComponent implements OnInit {
      public mobiles: any[];
      constructor(public http: Http) {
        console.log('AppComponent constructor :', 'run step constructor ');
        /**
          需要注意的是这里的请求文件的路径需要正确,
          所以一般都会有在公有文件中定义一个baseUrl从而来定位当前的文件位置,
          进而再获取文件从而获取数据。
        */
        http.get('../app/page/test/testHttp.json').subscribe(res=> 
            this.mobiles =res.json()
        );
      }
      ngOnInit() {
        console.log('AppComponent ngOnInit :', 'run step ngOnInit ');
      }
    }
    
    <!--
        testHttp.component.html
    -->
    <h1>Angular 2 App</h1>
    <ul *ngIf="mobiles">
      <li *ngFor="let m of mobiles"><span>{{m.id}}</span> {{m.name}}</li>
    </ul>
    

    angular的http模块

      HttpModule并不是Angular的核心模块。 它是Angular用来进行Web访问的一种可选方式,并位于一个名叫@angular/http的独立附属模块中,因此需要在app.module.ts中引入关于http的模块。

    import { HttpModule, JsonpModule } from '@angular/http';
    
    @NgModule({
      imports: [
        HttpModule,
        JsonpModule
      ],
    })
    

    angular官网的英雄编辑器的服务代码

    /*
      hero.ts
    */
    export class Hero {
        id: number;
        name: string;
    }
    /*
      hero.data.ts
    */
    import {Hero} from "./hero";
    export const HEROS: Hero[] = [
      {id: 1, name: 'Hero1'},
      {id: 2, name: 'Hero2'},
      {id: 3, name: 'Hero3'},
      {id: 4, name: 'Hero4'},
      {id: 5, name: 'Hero5'},
      {id: 6, name: 'Hero6'},
      {id: 7, name: 'Hero7'},
      {id: 8, name: 'Hero8'}
    ];
    /*
      hero.service.ts
    */
    import { Injectable } from '@angular/core';
    import {Hero} from "./hero";
    import {HEROS} from "./hero.data";
    
    @Injectable()
    export class HeroService {
      getHeros(): Promise<Hero[]> {
        return Promise.resolve(HEROS);
      }
      getMockHeros(): Promise<Hero[]> {
          return new Promise(resolve => setTimeout(resolve(HEROS), 2000))
            .then(() => this.getHeros());
        }
    }
    /*
      app.component.html
    */
    import {Component, OnInit} from '@angular/core';
    import {Hero} from "./User";
    import {HeroService} from "./special-user.service";
    /*
     * 别忘记了使用@前缀
     * 这里相当于组件视图
     */
    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
    })
    /*
     * 导出这个组件,也就是一个类
     * 这里相当于组件控制器
     */
    export class AppComponent implements OnInit{
        heros: Hero[];
        constructor(
          private heroService: HeroService
        ){}
        ngOnInit() {
            this.getHeroInfo();
        }
        public getHeroInfo () {
            this.heroService.getHeros().then(heros => {
                console.log(heros);
                this.heros = heros
            })
        }
    }
    /*
      app.component.html
    */
    <ul>
      <li *ngFor="let hero of heros">{{hero.name}}</li>
    </ul>

    代码资源

      angular实例代码中的angular-service,该项目中包含了angular服务的简单实例,也包含了angular英雄编辑器的请求服务的代码,还有我自己根据所学知识写的http服务请求数据的代码,希望能对读者有所帮助。

  • 相关阅读:
    中考 2020 游记
    CodeChef 2020 July Long Challenge 题解
    GDOI2020 游记
    AtCoder Grand Contest 044 题解
    ISIJ2020 不知道算不算游记
    WC2020 拿铁记
    UOJ Round 19 题解
    本博客采用 CC BY-NC-SA 4.0 进行许可
    [算法模版]回文树
    AddressSanitizer
  • 原文地址:https://www.cnblogs.com/shcrk/p/9231757.html
Copyright © 2011-2022 走看看