ABOUT ME

-

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

    http를 이용한 영웅 수정

    서비스에 update메소드를 추가한다.

    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}`;

        return this.http

          .put(url, hero)

          .toPromise()

          .then(() => hero)

          .catch(this.handleError);

      }

     

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

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

      }

    }

    HttpClient.put메소드를 이용하여 json객체를 파라메타로 호출한다.

     

    src/app/hero-detail.component.htm

    <div *ngIf="hero">

        <h2>{{hero.name}} 내역!</h2>

        <div><label>아이디 : </label>{{hero.id}}</div>

        <div>

            <label>이름 : </label>

            <div><input [(ngModel)]="hero.name" placeholder="영웅이름"></div>

        </div>

        <button (click)="save()">저장</button>

        <button (click)="goBack()">뒤로</button>

    </div>

    저장버튼의 click이벤트 발생시 save()메소드를 호출한다.

     

    src/app/hero-detail.component.t

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

    import { ActivatedRoute, ParamMap } from '@angular/router';

    import { Location } from '@angular/common';

    import 'rxjs/add/operator/switchMap';

     

    import { Hero } from './hero';

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

     

    @Component({

      selector: 'hero-detail',

      templateUrl: './hero-detail.component.html',

      styleUrls: ['./hero-detail.component.css']

    })

    export class HeroDetailComponent implements OnInit {

      hero: Hero;

     

      constructor(

        private heroService:HeroService,

        private route:ActivatedRoute,

        private location:Location

      ){}

     

      ngOnInit(): void{

        this.route.paramMap

        .switchMap((params: ParamMap) =>

          this.heroService.getHero(+params.get('id')))

          .subscribe(hero => this.hero = hero);

      }

     

      goBack():void{

        this.location.back();

      }

     

      save(): void {

        this.heroService.update(this.hero)

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

      }

    }

    컴포넌트에 save()메소드를 생성하여, 서비스의 update메소드를 호출한다.

    결과 콜백 메소드에 goBack()메소드를 호출하여 이전 화면으로 이동한다.

    댓글

Designed by Tistory.