ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 2-14 http를 이용한 영웅 추가
    앵귤러/01 퀵스타트 & 튜토리얼 2017. 8. 9. 09:09

    http를 이용한 영웅 추가

    서비스에 post메소드를 이용하여 추가 메소드를 생성한다.

    src/app/hero.service.ts

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

    import { HttpClient }       from '@angular/common/http';

    import 'rxjs/add/operator/toPromise';

     

    import { Hero } from './hero';

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

     

    @Injectable()

    export class HeroService {

      private heroesUrl = 'http://localhost:3000/heroes';

     

      constructor(private http:HttpClient){}

     

      getHeroes(): Promise<Hero[]> {

        return this.http.get(this.heroesUrl)

            .toPromise()

            .then(response => response as Hero[])

            .catch(this.handleError);

      }

     

      getHero(id:number):Promise<Hero> {

        const url = `${this.heroesUrl}/${id}`;

     

        return this.http.get(url)

          .toPromise()

          .then(response => response as Hero)

          .catch(this.getHeroes);

      }

     

      update(hero: Hero): Promise<Hero>{

        const url =`${this.heroesUrl}/${hero.id}`;

        console.log(url);

        console.log(JSON.stringify(hero));

        return this.http

          .put(url, hero)

          .toPromise()

          .then(() => hero)

          .catch(this.handleError);

      }

     

      create(name: string): Promise<Hero> {

        return this.http

        .post(this.heroesUrl, {name:name})

        .toPromise()

        .then(res => res as Hero)

        .catch(this.handleError);

      }

     

      private handleError(error: any): Promise<any> {

        return Promise.reject(error.message || error);

      }

    }

     

    영웅목록 컴포넌트의 html에 영웅의 이름을 등록하는 html을 추가한다.

    src/app/heroes.component.html

    <h2>나의 영웅들</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>

    <div *ngIf="selectedHero">

        <h2>

            {{selectedHero.name | uppercase}}() 나의 영웅입니다.

        </h2>

        <button (click)="gotoDetail()">세부내역 보기</button>

    </div>

    <div>

      <label>영웅 이름:</label> <input #heroName />

      <button (click)="add(heroName.value); heroName.value=''">

        추가

      </button>

    </div>

     

    영웅목록 컴포넌트에 추가기능 구현

    src/app/heroes.component.ts

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

    import { Router } from '@angular/router';

     

    import { Hero } from './hero';

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

     

    @Component({

      selector: 'my-heroes',

      templateUrl: './heroes.component.html',

      styleUrls: ['./heroes.component.css']

    })

    export class HeroesComponent implements OnInit {

      title = 'Tour of Heroes';

      heroes: Hero[];

      selectedHero: Hero;

     

      constructor(

        private router: Router,

        private heroService: HeroService

      ) { }

     

      getHeroes(): void {

        this.heroService.getHeroes()

          .then(heroes => this.heroes = heroes);

      }

     

      ngOnInit(): void {

        this.getHeroes();

      }

     

      onSelect(hero: Hero): void {

        this.selectedHero = hero;

      }

     

      gotoDetail():void{

        this.router.navigate(['/detail', this.selectedHero.id])

      }

     

      add(name:string): void{

        name = name.trim();

        if(!name) { return }

        this.heroService.create(name)

        .then(hero => {

          this.heroes.push(hero);

          this.selectedHero = null;

        });

      }

    }

     

    댓글

Designed by Tistory.