※当サイトの記事には、広告・プロモーションが含まれます。

EclipseでAngularJSのチュートリアル Services

今回は、AngularJSのチュートリアルの「Service」にトライしていきたいと思います。

Service

「Service」です。チュートリアルの説明によると、

As the Tour of Heroes app evolves, you'll add more components that need access to hero data.

Instead of copying and pasting the same code over and over, you'll create a single reusable data service and inject it into the components that need it. Using a separate service keeps components lean and focused on supporting the view, and makes it easy to unit-test components with a mock service.

Because data services are invariably asynchronous, you'll finish the page with a Promise-based version of the data service.

Angular Docs

再利用可能なデータサービスを作って、コンポーネントに挿入しようということらしいです。「DI(Dependecy Ingection)」、日本語でいうところの「依存性注入」みたいなイメージですかね? 

f:id:ts0818:20170916110248p:plain

JavaのSpring Bootでいうところの「Service」クラスに似た感じですかね?

Angular入門 | ぺーぺーSEのテックブログ

⇧  上記サイト様によると、「Service」自体を「DI(Dependecy Ingection)」していく感じになるようです。「DI(Dependecy Ingection)」ムズイっす。

 

チュートリアルをトライしていきたいと思います。

Angular Docs

f:id:ts0818:20170916163834j:plain

 live example / download example で完成系のサンプルを動かしたり、ソースのダウンロードができるようです。

 

前回までの「angular-tour-of-heroes」プロジェクトを使っていきます。

f:id:ts0818:20170916110808j:plain

コマンドプロンプトなどで、AngularJSの開発用サーバーを起動しておきます。

cd C:\workspace\firstSpring\src\main\resources\static\angular-tour-of-heroes
npm start

f:id:ts0818:20170916111306j:plain

「hero.service.ts」ファイルを新たに作ります。

「angular-tour-of-heroes」>「src」>「app」を選択した状態で右クリックし、「新規(W)」>「その他(O)...」を選択。

f:id:ts0818:20170916111532j:plain

「TypeScript」>「TypeScript Source File」を選択し、「次へ(N)>」

f:id:ts0818:20170916111911j:plain

「ファイル名(F):」を「hero.service.ts」とし「完了(F)」をクリック。

f:id:ts0818:20170916111710p:plain

同じ流れで、「mock-heroes.ts」ファイルも作成しておきます。

f:id:ts0818:20170916112318j:plain

ファイルを編集します。 

hero-service.ts

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

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

@Injectable()
export class HeroService {
  getHeroes(): Promise<Hero[]> {
    return Promise.resolve(HEROES);
  }
}

app.component.ts

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

import { Hero } from './hero';
import { HeroService } from './hero.service';


@Component({
  selector: 'my-app',
  // templateUrl: './app.component.html',
  // styleUrls: ['./app.component.css'],
  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]="selectHero"></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]
})
export class AppComponent implements OnInit {
  title = 'Tour of Heroes';
  heroes: Hero[];
  selectedHero: Hero;

  constructor(private heroService: HeroService) {}

  getHeroes(): void {
    this.heroService.getHeroes().then(heroes => this.heroes = heroes);
  }

  ngOnInit(): void {
    this.getHeroes();
  }

  onSelect(hero: Hero): void {
    this.selectedHero = hero;
  }
}

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' }
];

サーバーを再起動しないとエラーになってしまった...。コマンドプロンプトなどで「Ctrl + C」で一旦、サーバーを終了し、「npm start」でサーバーを再起動。

f:id:ts0818:20170916121349j:plain

ブラウザで『http://localhost:4200/』にアクセスすると、 

f:id:ts0818:20170916121825j:plain

表示されました。

TypeScriptの記述を覚えていかないとですね。 

今回はこのへんで。