Angular2服务

vue是MVVM框架中相对angular和react 比较容易入手的,有了vue的基础来看angular确实挺有帮助的,但是看到路由的时候,很多angular路由的TypeScript语法和思维确实有些让我转不过弯,下面我就来总结一下我学习完angular路由之后的一些心得。我们用angular官网的例子来讲解,文档代码(https://embed.plnkr.co/?show=preview

一、app文档里面的文档目录

--------app
----------app.component.ts
----------hero-detial.component.ts
----------app.module.ts
----------hero.services.ts
----------hero.ts
----------mock-heroes.ts
这几个文件分别有什么功能呢?

1.app.component.ts:根组件,将获取到的数据导入组件,渲染到页面上,并且传递给子组件
2.hero-detial.component.ts:子组件,接收父组件传递过来的数据并进行渲染
3.app.module.ts:声明HeroDetailComponent组件,只有声明了才可以使用
4.hero.services.ts:一个接口,一个请求获取数据的接口,请求到的数据可以被每个组件导入
5.hero.ts:声明一个类,并定义数据的类型
6.mock-heroes.ts:模拟数据库

接下来我们一一讲解一下里面的代码

二、代码讲解

1.app.component.ts

import { Component, OnInit } from '@angular/core';//导入类装饰器Component和生命周期钩子OnInit
 
import { Hero } from './hero';//导入hero.ts文件中定义的类
import { HeroService } from './hero.service';//导入hero.service.ts文件中请求到的数据
 
@Component({
  selector: 'app-root',//挂载
  /*模板可换成templateUrl,这个方法要创建一个文件,然后把template属性里面的HTML代码全部分离开来*/
  template: `          
    <h1>{{title}}</h1>
    <h2>My Heroes</h2>
    <ul class="heroes">
      <li *ngFor="let hero of heroes"
        [class.selected]="hero === selectedHero"
        (click)="onSelect(hero)">
        <span class="badge">{{hero.id}}</span> {{hero.name}}
      </li>
    </ul>
    <hero-detail [hero]="selectedHero"></hero-detail>
  `,
  styles: [`
    .selected {
      background-color: #CFD8DC !important;
      color: white;
    }
    .heroes {
      margin: 0 0 2em 0;
      list-style-type: none;
      padding: 0;
      width: 15em;
    }
    .heroes li {
      cursor: pointer;
      position: relative;
      left: 0;
      background-color: #EEE;
      margin: .5em;
      padding: .3em 0;
      height: 1.6em;
      border-radius: 4px;
    }
    .heroes li.selected:hover {
      background-color: #BBD8DC !important;
      color: white;
    }
    .heroes li:hover {
      color: #607D8B;
      background-color: #DDD;
      left: .1em;
    }
    .heroes .text {
      position: relative;
      top: -3px;
    }
    .heroes .badge {
      display: inline-block;
      font-size: small;
      color: white;
      padding: 0.8em 0.7em 0 0.7em;
      background-color: #607D8B;
      line-height: 1em;
      position: relative;
      left: -1px;
      top: -4px;
      height: 1.8em;
      margin-right: .8em;
      border-radius: 4px 0 0 4px;
    }
  `],
  providers: [HeroService]   //providers - 服务的创建者,并加入到全局服务列表中,这里的providers存在于app.component.ts这个模块中,
})                           //所以说,哪个组件需要请求到数据,哪个组件里面就加上providers声明一下数据来源于哪里,服务的创建者是谁
export class AppComponent implements OnInit {
  title = 'Tour of Heroes';
  heroes: Hero[];           //声明一个heroes变量,类型为Hero[],其实可以理解成为具有Hero类那种格式的数组
  selectedHero: Hero;       //声明一个selectedHero变量,类型为Hero
 
 /*
    *原来的写法是这样的heroService = new HeroService();但是 如果有一天我们修改了HeroService的构造函数,我们不得不找出创建过此服务的每一处代码,并修改它。
   */ 
  constructor(private heroService: HeroService) { }
  
 /*
    *getheroes函数里面的写法本来是这样的
     this.heroService.getHeroes().then(function(heroes){
      this.heroes = heroes;
     })
     把hero.service.ts文件中getHeroes()函数return的值通过heroes传进来,然后赋值给前面声明的heroes变量,此时所有的数据全部赋值给heroes变量了
  */
  getHeroes(): void {//void表示类型,因为getHeroes没有return值,所以为void
    this.heroService.getHeroes().then(heroes => this.heroes = heroes);//此处第一个heroes是一个参数,一个参数可以省略括号
  }
  //构造函数不应该包含复杂的逻辑
  ngOnInit(): void {
    this.getHeroes();//此处是调用上面声明并定义了的getHeroes()函数
  }
 
  onSelect(hero: Hero): void {
    this.selectedHero = hero;
  }
  /*
    此处用ES5写法就是
    function onSelect(hero){
      this.selectedHero = hero;
    }
    上面的Hero是限定hero的类型,void是限定onSelect函数的返回值类型
   */
}

2.hero-detial.component.ts

import { Component, Input } from '@angular/core';导入类装饰器Component和属性装饰器Input
import { Hero } from './hero';


@Component({
  selector: 'hero-detail', //定义标签名
  template: `
    <div *ngIf="hero">
      <h2>{{hero.name}} details!</h2>
      <div><label>id: </label>{{hero.id}}</div>
      <div>
        <label>name: </label>
        <input [(ngModel)]="hero.name" placeholder="name"/>
      </div>
    </div>
  `
})
export class HeroDetailComponent {
	@Input() hero: Hero;
}

3.app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule }   from '@angular/forms';
/*
  每个组件都必须在一个(且只有一个)Angular模块中声明。打开app.module.ts并且导入HeroDetailComponent,以便我们可以引用它。

 */

import { AppComponent } from './app.component';
import { HeroDetailComponent } from './hero-detail.component';


@NgModule({
  declarations: [   //把HeroDetailComponent添加到该模块的declarations数组中。
    AppComponent,
    HeroDetailComponent
  ],
  imports: [
    BrowserModule,
    FormsModule
  ],
  providers: [],//providers除了可以放置在需要用到的组件中之外,还可以放在app.module.ts这个核心文件中
  bootstrap: [AppComponent]  //bootstrap - 指定应用的主视图(称为根组件),它是所有其它视图的宿主。只有根模块才能设置bootstrap属性。
})
export class AppModule { }

4.hero.services.ts

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

import { Hero } from './hero';
import { HEROES } from './mock-heroes';

@Injectable()
/*
	此处是把HeroService的getHeroes方法改写为返回承诺的形式,原来的格式为
	 getHeroes(): Hero[] {
	    return HEROES;
	  }
 */
export class HeroService {
  getHeroes(): Promise<Hero[]> {
    return Promise.resolve(HEROES);
  }
}

5.hero.ts

export class Hero {
  id: number;
  name: string;
}

6.mock-heroes.ts

import { Hero } from './hero';
 
export const HEROES: Hero[] = [
  { id: 11, name: 'Mr. Nice' },
  { id: 12, name: 'Narco' },
  { id: 13, name: 'Bombasto' },
  { id: 14, name: 'Celeritas' },
  { id: 15, name: 'Magneta' },
  { id: 16, name: 'RubberMan' },
  { id: 17, name: 'Dynama' },
  { id: 18, name: 'Dr IQ' },
  { id: 19, name: 'Magma' },
  { id: 20, name: 'Tornado' }
];




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值