ionic入门之服务开发模式

xiaoxiao2021-02-28  75

本章在 ionic入门之多组件开发模式 基础上修改,创建服务用于多个view中调用,避免写重复的代码。

目录结构

新增加了 mock-heroes.ts hero.service.ts mock-heroes.ts,用来储存数据的hero.service.ts,用来支持服务

mock-heroes.ts

import { Hero } from './hero'; export const HEROES : Hero[] = [ { id : 101, name : '张三'}, { id : 102, name : '李四'}, { id : 103, name : '王五'}, { id : 104, name : '赵六'}, { id : 105, name : '陈七'}, { id : 106, name : '吴八'} ];

hero.service.ts

import { Injectable } from '@angular/core'; import { Hero } from './hero'; import { HEROES } from './mock-heroes'; // 注意,导入了 Angular 的Injectable函数,并作为@Injectable()装饰器使用这个函数。 @Injectable() export class HeroService{ getHeroes() : Promise<Hero[]>{ return Promise.resolve(HEROES); } getHeroesSlowly(): Promise<Hero[]> { return new Promise(resolve => { // 等待20秒之后在去调用方法 setTimeout(() => resolve(this.getHeroes()), 2000); }); } }

hero.component.ts

import {Component, OnInit} from '@angular/core'; import { Hero } from './hero'; import { HeroService } from './hero.service'; @Component({ selector : 'my-app', templateUrl : './hero.component.html', providers : [ HeroService ] }) //实现OnInit 并使用ngOnInit方法,在HeroComponent初始化后调用方法 export class HeroComponent implements OnInit{ title = '人物列表'; heroes : Hero[]; selectedHero : Hero; constructor(private heroService : HeroService){ } getHeroes() : void { // this.heroService.getHeroes().then(heroes => this.heroes = heroes); this.heroService.getHeroesSlowly().then(heroes => this.heroes = heroes); } ngOnInit() : void { this.getHeroes(); } onSelect(hero : Hero) : void { this.selectedHero = hero; } }

view

转载请注明原文地址: https://www.6miu.com/read-77531.html

最新回复(0)