반응형


서비스

영웅 관광 HeroesComponent는 현재 얻은 가짜 데이터를 표시 한다.

이 튜토리얼에서 다음의 리팩토링은 HeroesComponent은 뷰를 지원함에 있어 선택과 집중 할수 있다. 또한 목 서비스와 같이 단위테스트 쉽게 되게 할수 있다.


왜 서비스냐?

컴포넌트는  데이터를 직접가저오거나 바로 저장 하면 안된고 현재에 틀림없이 가짜 데이터라는것을 알고도 하면 안된다. 데이터 프리젠팅, 데이터 접근을 서비스로 위함하는데 집중해야 한다.

이 튜토리얼에서 모든 애플리케이션 클래스들이 영웅을 얻을 때 사용 할수 있는 HeroService 만들수 있다. 새로운 서비스를 만들는거 대신에,  HeroesComponent 생성자로 주입하는 앵귤라 의존성 주입에 의지 할 수 있다.

서비스는 알수없는 서로 다른 것을 클래스 사이에서 정보를 공유하기 좋은 방법이다. MessageService를 생성할수 있고 그것을 두곳에 주입 합니다.

HeroService에서는 서비스를 사용하여 메세지를 보낸다.

MessagesComponent에서는 메세지를 표시한다.


HeroService 생성

Angular CLI을 사용해 영웅을 호출하는 서비스를 생성합니다.

ng generate service hero

그 명령은 src/app/hero.service.ts 안에 HeroService 클래스의 뼈대를 자동생성합니다. 


PS D:\workspace\dev\angular02\angular-tour-of-heroes> ng generate service hero

  create src/app/hero.service.spec.ts (362 bytes)

  create src/app/hero.service.ts (110 bytes)

서비스는 테스트과 기능의 ts 파일 두개만 생성 하네요.


src/app/hero.service.ts (new service)

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

@Injectable()

export class HeroService {

  constructor() { }

}

@Injectable() 서비스

새로운 서비스는 앵귤라 Injectable 기호를 import 하고  @Injectable() 데코레이터를 클래스 옆에 애노테이트한것을 알수 있다.

@Injectable() 데코레이터는 Angular에게 이 서비스는 아마 그 자신은 주입된 의존성을 가진다라고 알려준다.  이것은 지금 의존성을 가지고 있지 않지만 곧 갖게 될것이다.  할수 있는지 혹은 할수 없든 decorator를 유지하는 것이 좋습니다.

앵귤라 스타일 가이드라인을 지키도록 강하게 권고하고 부스러기 린터는 그 룰대로 집행합니다.


영웅 데이터 얻기

HeroService 영웅 데이터는 웹서비스,  local storage, 혹은 가짜 데이터 중 어디서나 얻울수 있다.

콤포넌트에서 데이터 접근을 제거 하는것은 변할수 있는 너의 마음에 대해 언제든지, 어떤 컴포넌트의 간섭 없이 구현하는것을 의미한다. 그들은 서비스가 어떻게 일하는지 알수 없다.

이 튜토리얼 안에서 가짜 영웅들을 제공 하는것을 구현 할수 있다.


Her 와 HEROES Import

import { Hero } from './hero';

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

mock 영웅을 리턴하는 getHeroes 메소드를 추가한다.

getHeroes(): Hero[] {

  return HEROES;

}


HeroService 제공

의존성 주입 시스템에 HeroService를 제공해야  앵귤라가 HeroesComponent에 HeroService를 주입 할수 있다.

AppModule에 AppComponent안의 HeroesComponent에서 HeroService를 제공하는데에 몇몇방법이 있다. 각각 선택은 장단점을 가진다.

이 튜토리얼은 AppModule에서 제공하는것을 원한다.

앞서말한 인기있는 선택은 당신이 CLI에 전할수 있는 선택자 이다.  --module=app 추가하면 자동적으로 

ng generate service hero --module=app


AppModule 클래스를 열고, HeroService를 import 하고 , @NgModule.providers 배열을 추가한다.

src/app/app.module.ts (providers)

providers: [

    HeroService,

/* . . . */

  ],

providers 배열은 HeroService의 인스턴스를 공유하고, 그것을 뭍는 어떤 클래스로 주입하도록 앵귤라가 지시한다.

HeroService는   HeroesComponent에  지금 연결될 준비가 됬습니다.

이것은 잠정적인 코드 샘플이다. HeroService를 제공하고 사용하는것을 허락한다.  이쯤에서,  "최종 코드리뷰"안에  HeroService에서 코드는  다른 것이다.

Providers 가이드에서 제공자에 대하여 더 배웁니다.


HeroesComponent 업데이트

HeroesComponent 클래스 파일을 열어라.

더이상 원하지 않은 HEROES import를 삭제한다. 대신에 HeroService를 포함 합니다.

src/app/heroes/heroes.component.ts (import HeroService)

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

영웅 속성의 정의를 간단 선언으로 변경합니다.

heroes: Hero[];


HeroService 주입

생성자에 HeroService 타입의 개인 heroService 파라메터를 추가합니다.

constructor(private heroService: HeroService) { }

개인 heroService 속성을  파라메터는 동시에 정의되고 HeroService 주입 위치를 확인한다.

HeroesComponent를 앵규라가 생성할때, 의존성 주입 시스템은 heroService 파라메터를 HeroService의 싱글톤 인스턴스로 설정된다.


getHeroes() 추가

함수를 서비스에서 영웅들을 되찾아오는 것을 생성합니다.

getHeroes(): void {

  this.heroes = this.heroService.getHeroes();

}


ngOnInit 에서 요청

생성자에서 getHeroes() 실행 할때, 좋은 엽습이 아니다.

속성에 와이어 링 생성자 매개 변수와 같은 간단한 초기화를 위해 생성자를 예약하십시오. 생성자는 아무 것도해서는 안됩니다. 실제 데이터 서비스처럼 원격 서버에 HTTP 요청을하는 함수를 호출해서는 안됩니다.

대신에 getHeroes()를 ngOnInit 라이프사이틀 후크 내에서 호출하고, HeroesComponent 인스턴스를 생성한후 적절한 시점에 앵귤라는 ngOnInit를 호출 합니다.

ngOnInit() {

  this.getHeroes();

}


실행 보기

브라우저가 새로 고침되면 앱이 이전과 같이 실행되어 영웅의 목록과 영웅 이름을 클릭하면 영웅 상세보기가 표시됩니다.

반응형
반응형

주 / 상세 콤포넌트

현재  HeroesComponent 영웅들의 목록과 선택된 영웅의 상세 정보 둘다 표시된다

하나의 컴포넌트 안에 모든 특징을 보유한는것은  큰 애플리케이션을 유지 할수 없다. 각각 특정 작업 혹은 작업흐름 집중할수 있도록, 큰 컴포넌트를 더 작은 서브 컴포넌트로 분리하길 원한다. 

이페이지에서 재사용가능한  HeroDetailsComponent를 분리하는 방량의  첫번째 단계를 할수 있다.

HeroesComponent는 영웅들 목록에 있는 영웅들을 단지 내놓기만한다. HeroDetailsComponent 선택된 영웅의 상세를 내놓는다.


HeroDetailComponent 제작

Angular CLI를 사용해서 hero-detail 이름으로 새로운 컴포넌트를 자동생성한다.

ng generate component hero-detail

그 명령은 HeroDetailComponent 파일들과 AppModule에서 컴포넌트를 선언하는 것으로 골격을 이룬다.

PS D:\workspace\dev\angular02\angular-tour-of-heroes> ng generate component hero-detail

  create src/app/hero-detail/hero-detail.component.html (33 bytes)

  create src/app/hero-detail/hero-detail.component.spec.ts (660 bytes)

  create src/app/hero-detail/hero-detail.component.ts (297 bytes)

  create src/app/hero-detail/hero-detail.component.css (0 bytes)

  update src/app/app.module.ts (592 bytes)

실행된 내용이다. 관련 컴포넌트 이름으로 파일 4개를 만들고 app.module.ts 파일을 업데이트 했다.


템플릿 작성

영웅 상세 HTML을 HeroesComponent 템플릿 아래에서 자르고  HeroDetailComponent 템플릿의  그 생성된 표준문안 위에 붙혀넣는다. 

붙혀넣은 HTML은 selectedHero을 참조한다. 새로운 HeroDetailComponent   꼭 선택된 영웅 뿐만아니라 현재의 어떤 영웅을 줄 수 있다.  따라서  템플릿 안의 모든 "hero"를 "selectedHero"로  교체한다.

완료되면 HeroDetailComponent 템플릿 다음 처럼 보여야 한다.

src/app/hero-detail/hero-detail.component.html

<div *ngIf="hero">

  <h2>{{ hero.name | uppercase }} Details</h2>

  <div><span>id: </span>{{hero.id}}</div>

  <div>

    <label>name:

      <input [(ngModel)]="hero.name" placeholder="name"/>

    </label>

  </div>

</div>


영웅 속성에 @Input() 추가

HeroDetailComponent 템플릿은 콤포넌트에 Hero 유형의 영웅 속성에 바인드 된다.

HeroDetailComponent 클래스 파일을 열고  Hero symbol을 추가한다.

src/app/hero-detail/hero-detail.component.ts (import Hero)

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

영웅 속성은 Input 속성 @Input() 데코레이터로 애토테이트된 것이어야 야한다.  외부 HeroesComponent 다음과 같이 바인드 하기 때문이다.

<app-hero-detail [hero]="selectedHero"></app-hero-detail>

@angular/core import 문장을 Input을 추가하여  개정한다.

src/app/hero-detail/hero-detail.component.ts (import Input)

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

@Input() 데코레이를 영웅 속성 앞에 추가합니다.

@Input() hero: Hero;

저것은 만들고 싶은 HeroDetailComponent 클래스에 대해 변경해야할 유일한 변경사항입니다. 더이상 속성들이 없다. 프리젠테이션 로직이 아니다.

그 컴포넌트는 단순히 영웅 속성을 통해 영웅 개체를 수신하고 표시한다.


HeroDetailComponent를 보여주자.

HeroesComponent는 여진히  주/상세가 아닙니다.

그것의 자신을 영웅 상세를 표시하고, 템플릿의 일부를 자르기 전에것을 사용한다. 지금 이것은 HeroDetailComponent로 위임 할수 있다.

두개의 콤포넌트들은 부모/자식 관계를 가질수 있다.

그 부모 HeroesComponent 는  자식 HeroDetailComponent 를 보여주기 위해  보내진 새로운 영웅 사용자가 목록에서 영웅을 선택할때마다  제어 할것이다. 

HeroesComponent 클래스가 변하는것을 원치 않지만 그것의 템플릿을 변경 할 것이다.


HeroesComponent 템플릿 업데이트

HeroDetailComponent 선택자는 'app-hero-detail' 이다.

<app-hero-detail> 요소를 HeroesComponent 템플릿의 아래 부근에 추가하고 그곳에서 영웅 상세가  예전처럼 보여진다.

HeroesComponent.selectedHero 영우 속성의 요소로 바인드한다.


heroes.component.html (HeroDetail binding)

<app-hero-detail [hero]="selectedHero"></app-hero-detail>

[hero]="selectedHero" 은 앵귤라 속성을 바인딩하는 것이다.

이것은  selectedHero 에서  단방향 데이터 방인딩이다.

이제 사용자가 목록의 영웅을 클릭하면 selectedHero 변한다. 

selectedHero 변할때, 영웅이 속성 바인딩 업데이트 되고 HeroDetailComponent 그 새로운 영웅을 표시한다.

변경한 HeroesComponent 템플릿은 다음처럼 보인다.

heroes.component.html

<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>

<app-hero-detail [hero]="selectedHero"></app-hero-detail>

브라우저가 재생되고 앱 작업이 이전과 같이 재식작  된다 .


뭐가 바뀌었나?

앞에서와 같이, 매번 사용자가 영웅 이름을 클릭 할때마다, 그 영운 상세는 영웅 목록 아래로 나타난다. 지금 HeroDetailComponent는 HeroesComponent 대신에  그것들이 상세에 있는 것이다.

원래 HeroesComponent를 두개의 콤포넌트로 리팩토링하면 현재와 미래 모두 유익한 효과를 얻을수 있다.

HeroesComponent는 책임을 줄임으로서 간소화 했다.

부모 HeroesComponent의 간섭 없이 풍부한 영웅 수정자안에서 HeroDetailComponent를 진화 할수 있다.

영웅 상세 뷰의 간섭 없이  HeroesComponent는 진화 할수 있다.

어떤 미래 콤포넌트의 템플릿에서 HeroDetailComponent를 재사용 할수 있다.


마지막 코드 리뷰

src/app/hero-detail/hero-detail.component.ts

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

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

 

@Component({

  selector: 'app-hero-detail',

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

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

})

export class HeroDetailComponent implements OnInit {

  @Input() hero: Hero;

 

  constructor() { }

 

  ngOnInit() {

  }

}


src/app/hero-detail/hero-detail.component.html

<div *ngIf="hero"> <h2>{{ hero.name | uppercase }} Details</h2> <div><span>id: </span>{{hero.id}}</div> <div> <label>name: <input [(ngModel)]="hero.name" placeholder="name"/> </label> </div> </div>


src/app/heroes/heroes.component.html

<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> <app-hero-detail [hero]="selectedHero"></app-hero-detail>


요약

별도의 재사용 할수 있는 HeroDetailComponent를  생성된다.

부모 HeroesComponent는 자식 HeroDetailComponent에 대한 통제를 준는것을 속성바인딩을 사용한다.

@Input 데코레이터는 확장 HeroesComponent으로 빌등 가능한 영웅 속성을  만들때 사용한다.



반응형
반응형

영웅 목록 표시

이페이지에서는 영웅 여행 앱이 영웅 목록을 표시하는것을 확장할수 있고,  사용자가 선택한 그영웅의 정보를 표시하는것을 허용한다.


모형 영웅 생성

우리는 표시하고 싶은 영웅들이 필요합니다.

결국 원격 데이터 서버에서 영웅정보를 얻을수 있습니다. 현재로는(당분간은) 어떤 모형 영웅들을 만들고 서버에서 온것처럼 할것이다.

mock-heroes.ts 파일을 src/app/ 폴더속에 만들자. HEROES 상수를 열개의 영웅과 export 한 배열로 정의한다. 

src/app/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' }

];


영웅을 표시

이제  HeroesComponent에 영웅목록에서 제일 위에 것에 표시 할때이다.

HeroesComponent 클래스 파일을 열고 mock HEROES을 import 한다.


src/app/heroes/heroes.component.ts (import HEROES)

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


영웅들의 속성을 영웅들이 드러나게 빌딩된 것을 클래스에 추가한다.

heroes = HEROES;


*ngFor로 영웅 목록

HeroesComponent 템플릿 파일을 열고 다음과 같이 수정한다.


<h2>를 위에 추가합니다.

그 밑에 HTML 순서가 없는 목록인 <ul> 코드를 추가.

<li>를  영웅의 표시되는 속성을 <ul> 사이에 삽입한다. 

스타일을 위해 CSS 클래스를 간간히 썩어라.

아래처럼 만든다.

heroes.component.html (heroes template)

<h2>My Heroes</h2>

<ul class="heroes">

  <li>

    <span class="badge">{{hero.id}}</span> {{hero.name}}

  </li>

</ul>


지금 <li>를 아래 처럼 바꾼다.

<li *ngFor="let hero of heroes">

*ngFor  앵귤라의 반복 디렉티브다. 리스트의 요소를 반복해서 합니다.

  • <li>은 주 요소입니다.
  • heroes 은 HeroesComponent 클래스에서 정의된 목록이다.
  • 영웅은 그 각의 목록의 반복을 통한 각각의 현재 영웅 객체를 잡고 있다.


ngFor 앞에 *은 잊지말고 쓰자. 문법이니까..

브라우저가 재생된 후에 영웅들의 목록이 나타난다.


영웅의 스타일

영웅 목록은 매력적이고 이어야하고, 사용자가 위에 맴돌때와 목록에서 선택된 영웅이 반응형이어야 한다.

첫번재 튜토리얼에서  styles.css으로 온 애플리케이션을 위한 기본 스타일을 해놓았다. 그 스타일쉬트는 영웅들 목록을 위한 스타일을 포함하지 않는다.

스타일들을 styles.css에  추가할수 있고 스타일시트가 커지지 않케 유지할수 있다.

 HTML, CSS  한곳에서 유지 하는것을 선호 할수 도 있습니다.

이방법을 사용하면 재상용이 가능이 쉽다.

개인 스타일  @Component.styles에 인라인 혹은 @Component.styleUrls 배열로 스타일시트 파일로 정의 합니다.

HeroesComponent가 CLI 자동생성 될때, HeroesComponent를 위한 heroes.component.css 스타일 시트가 생성되고 @Component.styleUrls 다음처럼 가리킨다.


src/app/heroes/heroes.component.ts (@Component)

@Component({

  selector: 'app-heroes',

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

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

})

heroes.component.css 파일을 열고  HeroesComponent 만을 위한 CSS 스타일에 붙혀넣는다.  마지막코드 리뷰의 마지막 안내에 찾을수 있다.

스타일과 스타일시트는 @Component 메타데이터는 특정 컴포넌트에 속한 영역에 선언한다.  heroes.component.css 스타일은 HeroesComponent  에만 적용된다..


Master/Detail

주 목록에서 영웅을 사용자가 클릭 할때, 콤포넌트는 선택된 영웅의 상세를 페이지 아래에 표시 해야한다.

이번 섹션에서는 영웅 항목 클릭 이벤트에 와 영웅 상세정보를 업데이트하는 것에 대해 들을수 있다.


클릭 이벤트 바인딩을 추가한다.

아래처럼 <li> 클릭 이벤트 바인딩을 추가한다.

heroes.component.html (template excerpt)

<li *ngFor="let hero of heroes" (click)="onSelect(hero)">


앵귤라의 이벤트 바딩인 문법 예제입니다.

괄호 주위 click을 <li>요소들이 클릭이벤트를  엥귤라에게 알린다. 사용자가 <li>테그를 클릭 할때, 앵귤라는  onSelect(hero) 표현이 실행된다.

onSelect()는 HeroesComponent에 작성한 대한 메소드이다. 앵귤라는 <li>클릭시에 표시된 영웅 객체를 부른다, 그 같은 영웅은 *ngFor 표현식으로 이전에 정의된다.


클릭 이벤트 핸들러 추가

컴포넌트의 영웅 속성 selectedHero 으로 이름을 바꾼다.  그러나 이것을 배정 하지 않는다. 저것은 애플리케이션이 시작될때 선택되지 않은 영웅이다.

다음으로 onSelect() 메소드를 추가, 어떤 컴포넌으의 selectedHero 템플릿으로부터 그 선택된 영웅을 배정한다.


src/app/heroes/heroes.component.ts (onSelect)

selectedHero: Hero;

onSelect(hero: Hero): void {

  this.selectedHero = hero;

}


상세 템플릿을 업데이트한다.


The template still refers to the component's old hero property which no longer exists. Rename hero to selectedHero.

템플릿은 컴포넌트의 이미 존재하지 않은 오래된 속성을 여전히 참조하고 있다. hero 에서  selectedHero으로 이름을 바꾼다.


heroes.component.html (selected hero details)

<h2>{{ selectedHero.name | uppercase }} Details</h2>

<div><span>id: </span>{{selectedHero.id}}</div>

<div>

  <label>name:

    <input [(ngModel)]="selectedHero.name" placeholder="name">

  </label>

</div>


빈 상세정보는 *ngIf 로 숨겨진다.

브라우저 재생 된후 애플리케이션은 깨진다.

브라우저 개발툴을 열고 에러메세지가 다음과 같은 콜솔을 본다.

HeroesComponent.html:3 ERROR TypeError: Cannot read property 'name' of undefined

이제 목록 항목중 하나를 클릭합니다. 앱은 다시 동작되는것처럼 보인다.  영웅이 목록과 선택된 영우에 대한 상세 나타난다 페이지 하단에 보이기 사작한다.


무슨일일까?

앱이시작 될때, selectedHero은 고의로 정의되지 않았다.

선택된지 않은 영웅이기 때문에   {{selectedHero.name}}의 표현은 바인딩에 실패한다.


해결책

컴포넌트는 selectedHero가 존재하면 선택된 영웅 상세를 단지 보여주기 해야한다 

<div> 안에 영웅 상세 HTML  싸여져 있다. 앵귤라의 *ngIf 디렉티브를  <div> 에 추가하고 이것을 selectedHero에 설정한다.

ngIf 앞에 *쓰는것을  잊지말아. 중요한 문법중의 하나다.


src/app/heroes/heroes.component.html (*ngIf)

<div *ngIf="selectedHero">

  <h2>{{ selectedHero.name | uppercase }} Details</h2>

  <div><span>id: </span>{{selectedHero.id}}</div>

  <div>

    <label>name:

      <input [(ngModel)]="selectedHero.name" placeholder="name">

    </label>

  </div>

</div>


브라우저가 재생된 후에 이름 목록이 다시 나타난다.   상세 영역은 비어있다. 영웅을 클릭하면 상세정가 나타난다.


어떻게 돌아가나.

selectedHero가 정의되지 않앗을때, ngIf는 DOM에서 영웅 상세정보를 제거한다. 그것들은 selectedHero 바인딩이 아닌 것에 대해서 걱정한다.

사용자가 영웅을 골랐을때, selectedHero 값을 가지고 ngIf는 DOM안에 영웅 상세를 넣는다.


선택된 영웅 스타일

모든 <li>요소가 보이는 목록에서  선택된 영웅을 확인하기가 어렵다.

사용자가 "Magneta"를 클릭 했을때, 영웅은   독특하게 민들 어야만 하나 미묘한 백그라운드 칼라는 다음과 같다.

선택된 영웅 색은 먼저 추가된 스타일 에 .selected css 클래스에 일한다. 사용자가 이것을 클릭 했을대 .selected 클래스를 <li>에 반드시 적용해야한다.

앵귤라 클래스 바인딩은  조건부 CSS 클래스를 추가 / 제거를 쉽게 만든다. [class.some-css-class]="some-condition"를 원하는 스나일 요소에 반드시 추가 하기만 하면 된다.

Add the following [class.selected] binding to the <li> in the HeroesComponent template:

다음의 [class.selected]를  HeroesComponent 템플릿의 <li>으로 바인딩을 추가한다.


heroes.component.html (toggle the 'selected' CSS class)

[class.selected]="hero === selectedHero"


현재 영웅 줄은 selectedHero와 같다. 앵귤라 선택된 CSS 클래스를 추가한다. 두 영웅은 다를 때, 앵귤라는 그 클래스를 제거한다.

완성된 <li> 는 이렇게 보인다.


heroes.component.html (list item hero)

<li *ngFor="let hero of heroes"

  [class.selected]="hero === selectedHero"

  (click)="onSelect(hero)">

  <span class="badge">{{hero.id}}</span> {{hero.name}}

</li>



최종 코드 리뷰

src/app/heroes/heroes.component.ts

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

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

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

 

@Component({

  selector: 'app-heroes',

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

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

})

export class HeroesComponent implements OnInit {

 

  heroes = HEROES;

 

  selectedHero: Hero;

 

 

  constructor() { }

 

  ngOnInit() {

  }

 

  onSelect(hero: Hero): void {

    this.selectedHero = hero;

  }

}

src/app/heroes/heroes.component.html

<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>

<div *ngIf="selectedHero">

  <h2>{{ selectedHero.name | uppercase }} Details</h2>

  <div><span>id: </span>{{selectedHero.id}}</div>

  <div>

    <label>name:

      <input [(ngModel)]="selectedHero.name" placeholder="name">

    </label>

  </div>

 </div>

src/app/heroes/heroes.component.css

/* HeroesComponent's private CSS 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;

}

요약

영웅의 여행 앱은 영웅 목록을 주 / 상세 뷰에서 표시된다.

사용자는 영웅을 선택할수 있고 영웅의 상세정보를 볼수 있다.

목록을 표시할때는 *ngFor 이용한다.

*ngIf 는 HTML 블럭을 선택적으로 포함 혹은 제외  한다.

클래스 바인딩을 통해 CSS스타일을 토글 할수 있다.


반응형
반응형

영웅 수정

사용자는 <input> 텍스트박스 안에 영웅 이름을 수정할 수 있어야 한다.

텍스트박스 영우의 이름이 표시되고 사용자 타입 속성을 업데이트 한다. 

즉 데이터의 흐름은  컴포넌트 클래스에서 화면으로 표시되고 화면에서 클래스로 흐름이다.

데이터의 흐름을 자동화 하는것은, 요소의 <input>과 hero.name 속성을 양방향 데이터 바인딩으로 설정 한다.


양방향 바인딩

HeroesComponent 템플릿에 상세소스

src/app/heroes/heroes.component.html (HeroesComponent's template)

<div>

    <label>name:

      <input [(ngModel)]="hero.name" placeholder="name">

    </label>

</div>

[(ngModel)]은 앵귤러의 양방향 데이터 바인딩 문법이다.


여기 hero.name 속성은 HTML 텍스트박스에 바인딩 되고 데이터는 양방향으로 흐를수 있다. hero.name 속성 에서 텍스트박스로, 그리고 텍스트 박스는 hero.name 으로 돌아간다.


누락된 FormsModule

(ngModel) 을 추가 하면 앱이 동작하지 않는다.

에러를 보면, 브라우저의 개발툴과 다음과 같은 메세를 콘솔에서 확인한다.


Template parse errors:

Can't bind to 'ngModel' since it isn't a known property of 'input'.


크롬 에서 확인

Uncaught Error: Template parse errors:

Can't bind to 'ngModel' since it isn't a known property of 'input'. ("<div>

    <label>name:

      <input [ERROR ->][(ngModel)]="hero.name" placeholder="name">

    </label>

</div>"): ng:///AppModule/HeroesComponent.html@2:13

    at syntaxError (compiler.js:485)

    at TemplateParser.parse (compiler.js:24668)

    at JitCompiler._parseTemplate (compiler.js:34621)

    at JitCompiler._compileTemplate (compiler.js:34596)

    at eval (compiler.js:34497)

    at Set.forEach (<anonymous>)

    at JitCompiler._compileComponents (compiler.js:34497)

    at eval (compiler.js:34367)

    at Object.then (compiler.js:474)

    at JitCompiler._compileModuleAndComponents (compiler.js:34366)


ngModel은 유효한 앵귤러 명령 이긴하지만, 기본적으로 사용할수 없다.

선택적 FormsModule 이어서, 사용 할려면 옵션을 넣어야 한다.


AppModule

앵귤라는 반드시 애플리케이션 조각들이 어떻게  서로 잘 맞는지, 무슨 다른 파일들과 앱에서 필요로 하는 라이브러리들을 알아야 합니다. 이 정보를 메타데이터라고 불린다.

메타데이터 중의 일부는  컴포넌트 클래스들을 추가할 @Component 데코레이터이다. 메타데이터의 대단의 중요한 것은 @NgModule 데코레이터에 있다.

제일 중요한 @NgModule 데코레이터 애노테이트는 최상위 AppModule 클래스이다.

프로젝트가 생성될때 AppModule 클래스가 src/app/app.module.ts 코드에 Angular CLI이 자동생성된다. 


이것은 FormsModule 에서  옵션을 넣을때.


FormsModule 추가

AppModule(app.module.ts) 열고 @angular/forms 라이브러리에서 FormsModule 심볼을 가져옵니다.


app.module.ts (FormsModule 추가)

import { FormsModule } from '@angular/forms'; // <-- NgModel lives here


FormsModule을 추가 할때  @NgModule 메터데이터의 배열을 추가한다. 이 배열에 포함된것은 앱에 필요한것을 확장 모듈 목록 이다.


app.module.ts ( @NgModule imports)

imports: [

  BrowserModule,

  FormsModule 

],

브라우저가 재생될때, 앱이 다시 작동 한다.  영웅의 이름을 수정할수 있고, textbox 위에 <h2> 변화되는 즉각 반응하는 모습을 볼수 있다.


HeroesComponent 선언

모든 컴포넌트는 정확히 하나의 NgModule로 선언되어야 한다.

HeroesComponent를 선언하지 않았습니다. 그렇다면 애플리캐이션이 왜 작동 할까요?

그게 작동한 이유는 Angular CLI이 AppModule에서 HeroesComponent 콤포넌트가 자동생성될때 이를 선언했기 때문이다.

src/app/app.module.ts 파일을 열어서  HeroesComponent  찾아 위부근에 추가한다.

import { HeroesComponent } from './heroes/heroes.component';


The HeroesComponent is declared in the @NgModule.declarations array.

declarations: [

  AppComponent,

  HeroesComponent

],

애플리케이션 콤포넌트, AppComponent 와 HeroesComponent AppModule 선언한다.


최종 코드 검토


src/app/heroes/heroes.component.ts

src/app/heroes/heroes.component.html

src/app/app.module.ts

src/app/app.component.ts

src/app/app.component.html

src/app/hero.ts

content_copy

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

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

 

@Component({

  selector: 'app-heroes',

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

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

})

export class HeroesComponent implements OnInit {

  hero: Hero = {

    id: 1,

    name: 'Windstorm'

  };

 

  constructor() { }

 

  ngOnInit() {

  }

}


요약

CLI로 사용하여 두번재 HeroesComponent 생성했다.

HeroesComponent에 AppComponent로 추가하여 표시했다.

UppercasePipe 적용하여 이름 서식을 지정 했다.

양방향 데이터 바인딩은 ngModel 디렉티브를 이용했다.

AppModule에 대해서 배웠다.

AppModule에서  FormsModule을 추가 하면 앵귤라는 그것을 알아채고 ngModel 디렉티브를 지원한다.

AppModule에서 컴포넌트선언의 중요성을 배웠고 당신을 위한 CLI 선언 진가를 알아봤다.


반응형
반응형

영웅 수정

애플리케이션은 이제 기본 제목이 있다. 다음으로 영웅정보 표현과 애플리케이션 쉘의 콤포넌트의 배치 할 새로운 콤포넌트를 만든다.


영웅 콤포넌트 만들기

앵귤라 CLI를 이용해서 heroes라는 이름으로 새로운 콤포넌트를  자동생성한다.

ng generate component heroes



ng : 'ng' 용어가 cmdlet, 함수, 스크립트 파일 또는 실행할 수 있는 프로그램 이름으로 인식되지 않습니다. 이름이 정확한지 확인하고 경로가 포함된 경우 경로가 올바른지 검증한 다음 다시 시도하십시오.

위치 줄:1 문자:1

+ ng generate component heroes

+ ~~~

    + CategoryInfo          : ObjectNotFound: (ng:String) [], CommandNotFoundException

    + FullyQualifiedErrorId : CommandNotFoundException


angular/cli 이 설치가 안되었나 해서 angular/cli  설치후 다시실 행 똑 같은 오류 ..

이상하다 싶었다.

ls 명령어 후 다시 컴포넌트 재너레이터 명령 실행하니 5초 정도 걸린후 제너레이터 된 파일이 만들어졌다. 


PS D:\workspace\dev\angular02\angular-tour-of-heroes> ng generate component heroes

  create src/app/heroes/heroes.component.html (25 bytes)

  create src/app/heroes/heroes.component.spec.ts (628 bytes)

  create src/app/heroes/heroes.component.ts (269 bytes)

  create src/app/heroes/heroes.component.css (0 bytes)

  update src/app/app.module.ts (398 bytes)

html과 테스트, ts파일, css 파일이 제너레이터 되어 생성되고, 모듈 파일이 업데이트 되었다.


CLI은 src/app/heroes/ 폴더를 만들고 HeroesComponent의 3개 파일이 자동생성된다.


HeroesComponent 클래스 파일은  다음과 같다.

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


@Component({

  selector: 'app-heroes',

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

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

})

export class HeroesComponent implements OnInit {


  constructor() { }


  ngOnInit() {

  }

}

앵귤러 코어 라이브러리를 항상 import 해야된다네요. 그리고 @Component 애노테이션을 함깨 사용한다고 합니다.

@Component는  콤포넌트를 위한 Angular 메터데이터를  명시하는 decorator 이다.

CLI은 3개 메테데이터 속성을 자동생성한다.

  1. selector - 콤포넌트의 CSS 요소 선택자
  2. templateUrl - 콤포넌트의 템플릿 파일이 위치 
  3. styleUrls - 콤포넌트마느이 CSS 스타일 위치


CSS 요소 선택자, 'app-heroes', 이컴포넌트가 부모 컴포넌트의 템플릿에서 확인  html 요소의 이름이 같은것을 매치한다.

컴포넌트 생성 후 바로 싱행된는  ngOnInit는  초기화 로직을 넣기에 좋은 곳이다.

 AppModule 안에 처럼  다른곳에서 가져올수 있도록 항상 컴포넌트 클래스를 내보낸다.  


영웅 속성 추가


영웅이름을 "Windstorm" 으로 HeroesComponent 에 영웅 속성을 추가한다.

heroes.component.ts (hero property)

hero = 'Windstorm';


영웅 보여주기.

heroes.component.html 템플릿 파일을 연다.  Angular CLI 가 자동으로 만든 기본 글을 삭제하고 새로운 영웅 속성 데이터 바인을 변경한다.


heroes.component.html

{{hero}}


HeroesComponent view 보여주기

HeroesComponent를 보여주는것은  shell AppComponent의 템플릿을 추가 해야한다.

app-heroes는 HeroesComponent의 요소 선택자를  기억해라. AppComponent 템플릿 파일에 <app-heroes> 요소를 정확히 title 아래 추가한다, 


src/app/app.component.html

<h1>{{title}}</h1>

<app-heroes></app-heroes>

ng serve 명령을 이용해서 title 과 영웅 이름을 표시를 확인한다.


영웅 클래스 생성

src/app 폴더 안에 자신의 파일을 id와 name 속성을 줘서 영웅 클래스를 생성한다. .


src/app/hero.ts

export class Hero {

  id: number;

  name: string;

}


HeroesComponent 클래스로 돌아와서 Hero 클래스를 가져온다.

컴포넌트의 영웅 프로퍼티 는 Hero 타입으로  리팩터한다. 초기화설정은 1의 id 와  Windstorm 이름으로한다.

수정된 HeroesComponent클래스 파일은 다음 과 같다.

src/app/heroes/heroes.component.ts

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

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


@Component({

  selector: 'app-heroes',

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

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

})

export class HeroesComponent implements OnInit {

  hero: Hero = {

    id: 1,

    name: 'Windstorm'

  };


  constructor() { }


  ngOnInit() {

  }

}


이페이지는 더이상 적절히 표시되지 않는다. 왜냐면 문자열에서 객체로 변경된 영웅 폼 때문이다.

 [object Object] 로 표시된다.


영웅 객체 표시

템플릿 안에서 상세 레이아웃 안에서 영웅의 이름과 id 그리고 이름을 보여주는것을 알려주는  바인딩 업데이트 한다.

heroes.component.html (HeroesComponent's template)

<h2>{{ hero.name }} Details</h2>

<div><span>id: </span>{{hero.id}}</div>

<div><span>name: </span>{{hero.name}}</div>

브라우저 리프래쉬되고 영웅의 정보를 보여준다.


대문자 파이프 포멧

이처럼 hero.name 바인딩을 수정한다.

<h2>{{ hero.name | uppercase }} Details</h2>

브라우저 리플래시되고 지금 바로 영웅의 이름은 대문자로 표시된다.

대문자를 바인딩을 써넣을때 , 파이프 연산자 | 바로뒤, 내장 UppercasePipe를 동작시킨다

파이프는 문자열 포메팅, 통화 가격, 날짜 와 다른 날짜 표시에 함에 좋은 방법이다.    


반응형
반응형


Angular CLI 설치


Angular CLI 설치 , 이미 했으면 안해도 된다.

npm install -g @angular/cli

이미 설치 했는데 진행해 보았다.

먼가 추가되고 업데이트 되고 지워지면서 업데이트 되는것 처럼 보였다.


.......

+ @angular/cli@1.7.4

added 179 packages, removed 272 packages, updated 134 packages and moved 14 packages in 45.039s



새로운 앱 생성


CLI 명령을 통해 새로운 프로젝트를 angular-tour-of-heroes 라는 이름으로 생성한다.

ng new angular-tour-of-heroes

Angular CLI 기본적인 앱과 지원하는 파일들과 같이 새로운 프로젝트가 자동생성된다.


PS D:\workspace\dev\angular02> ng new angular-tour-of-heroes

  create angular-tour-of-heroes/e2e/app.e2e-spec.ts (304 bytes)

  create angular-tour-of-heroes/e2e/app.po.ts (208 bytes)

  create angular-tour-of-heroes/e2e/tsconfig.e2e.json (235 bytes)

  create angular-tour-of-heroes/karma.conf.js (923 bytes)

  create angular-tour-of-heroes/package.json (1307 bytes)

  create angular-tour-of-heroes/protractor.conf.js (722 bytes)

  create angular-tour-of-heroes/README.md (1035 bytes)

  create angular-tour-of-heroes/tsconfig.json (363 bytes)

  create angular-tour-of-heroes/tslint.json (3012 bytes)

  create angular-tour-of-heroes/.angular-cli.json (1257 bytes)

  create angular-tour-of-heroes/.editorconfig (245 bytes)

  create angular-tour-of-heroes/.gitignore (544 bytes)

  create angular-tour-of-heroes/src/assets/.gitkeep (0 bytes)

  create angular-tour-of-heroes/src/environments/environment.prod.ts (51 bytes)

  create angular-tour-of-heroes/src/environments/environment.ts (387 bytes)

  create angular-tour-of-heroes/src/favicon.ico (5430 bytes)

  create angular-tour-of-heroes/src/index.html (306 bytes)

  create angular-tour-of-heroes/src/main.ts (370 bytes)

  create angular-tour-of-heroes/src/polyfills.ts (3114 bytes)

  create angular-tour-of-heroes/src/styles.css (80 bytes)

  create angular-tour-of-heroes/src/test.ts (642 bytes)

  create angular-tour-of-heroes/src/tsconfig.app.json (211 bytes)

  create angular-tour-of-heroes/src/tsconfig.spec.json (283 bytes)

  create angular-tour-of-heroes/src/typings.d.ts (104 bytes)

  create angular-tour-of-heroes/src/app/app.module.ts (316 bytes)

  create angular-tour-of-heroes/src/app/app.component.html (1141 bytes)

  create angular-tour-of-heroes/src/app/app.component.spec.ts (986 bytes)

  create angular-tour-of-heroes/src/app/app.component.ts (207 bytes)

  create angular-tour-of-heroes/src/app/app.component.css (0 bytes)

npm WARN deprecated nodemailer@2.7.2: All versions below 4.0.1 of Nodemailer are deprecated. See https://nodemailer.com/status/

npm WARN deprecated mailcomposer@4.0.1: This project is unmaintained

npm WARN deprecated socks@1.1.9: If using 2.x branch, please upgrade to at least 2.1.6 to avoid a serious bug with socket data flow and an import issue introduced in 2.1.0

npm WARN deprecated node-uuid@1.4.8: Use uuid module instead

npm WARN deprecated buildmail@4.0.1: This project is unmaintained

npm WARN deprecated socks@1.1.10: If using 2.x branch, please upgrade to at least 2.1.6 to avoid a serious bug with socket data flow and an import issue introduced in 2.1.0


> uws@9.14.0 install D:\workspace\dev\angular02\angular-tour-of-heroes\node_modules\uws

> node-gyp rebuild > build_log.txt 2>&1 || exit 0



> node-sass@4.8.3 install D:\workspace\dev\angular02\angular-tour-of-heroes\node_modules\node-sass

> node scripts/install.js


Cached binary found at C:\Users\oldma\AppData\Roaming\npm-cache\node-sass\4.8.3\win32-x64-57_binding.node


> uglifyjs-webpack-plugin@0.4.6 postinstall D:\workspace\dev\angular02\angular-tour-of-heroes\node_modules\webpack\node_modules\uglifyjs-webpack-plugin

> node lib/post_install.js



> node-sass@4.8.3 postinstall D:\workspace\dev\angular02\angular-tour-of-heroes\node_modules\node-sass

> node scripts/build.js


Binary found at D:\workspace\dev\angular02\angular-tour-of-heroes\node_modules\node-sass\vendor\win32-x64-57\binding.node

Testing binary

Binary is fine

npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.1.3 (node_modules\fsevents):

npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.1.3: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})


added 1382 packages in 154.975s

Project 'angular-tour-of-heroes' successfully created.


맨아래 성공적으로 프로젝트가 만들어졌다고 한다.

기본파일처음에 생성하고 deprecated 에 대한 경고 나오는거 보니 라이브러리의 의존성 체크도 하나보다.

노드관련 모듈 머시기 설치하고 빌드하고 하는것 같고 ( 노드도 배우얄 탠데)


애플리케이션 서버

프로젝트 디렉토리로 이동하고 앱을 시작합니다.

cd angular-tour-of-heroes

ng serve --open

ng serve 명령어는 앱을 빌드, 개발서버에서 시작, 소스 파일을 봐주고, 파일을 수정해서 앱을 리빌드한다.

--open 플래그는 브라우저를 http://localhost:4200/로 열어준다.

브라우저에서 앱이 실행되는것이 보인다.


PS D:\workspace\dev\angular02\angular-tour-of-heroes> ng serve --open

** NG Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200/ **

 10% building modules 7/11 modules 4 active ...our-of-heroes\node_modules\url\url.jswebpack: wait until bundle finished: /   Date: 2018-04-06T00:33:28.449ZHash: 4802a752f2c2aa4cfe70

Time: 6533ms

chunk {inline} inline.bundle.js (inline) 3.85 kB [entry] [rendered]

chunk {main} main.bundle.js (main) 18 kB [initial] [rendered]

chunk {polyfills} polyfills.bundle.js (polyfills) 554 kB [initial] [rendered]

chunk {styles} styles.bundle.js (styles) 41.5 kB [initial] [rendered]

chunk {vendor} vendor.bundle.js (vendor) 7.42 MB [initial] [rendered]


webpack: Compiled successfully.


브라우저(IE) 띄어지고 자동으로 http://localhost:4200/ 경로가 열렸다.

브라우저는 윈도우 기본브라우저가 열리는듯 한다. 브라우저 선택도 어딘가에 설정이 있을듯 한데..

자동으로 열림 IE 에서 화면에 아무것도 보여지지 않고, 크롬에서 열어야 기본 앵귤러 화면이 보인다.


Angular components

페이지에서 애플리케이션 shell이 보인다. shell은 AppComponent라는 Angular component에 의해서 제어 된다.

콤포넌트는 앵귤러 애플러케이션의 기본 구성요소다. 화면에 데이터를 표시하고, 사용자의 입력을 감지하고, 그리고 입력에의 기본조치를 한다.


애플리케이션 제목 변경

즐겨쓰는 에디터나 IDE로 프로젝트를 열고 src/app 폴더를 찾는다.

3개의 파일로 배포된  shll AppComponent 의구현된 것을 확인 할수 있다.


  1. app.component.ts - component 클래스 코드, TypeScript로 작성된다.
  2. app.component.html - component template, html 로 작성된다.
  3. app.component.css - 콤퍼넌트 만의 CSS 스타일이다.


component class file(app.component.ts)을 열고 title 속성의 값을 'Tour of Heroes'로 변경  합니다.

title = 'Tour of Heroes';


component template file (app.component.html) 을 열고 Angular CLI로 기본 템플릿으로 만들어진 것을 삭제 합니다. 다음의 HTML 라인안에 것으로 교체 합니다.

<h1>{{title}}</h1>


이중 중괄호 {{ }} 는 엥귤라를 써넣는 바인딩 문법이다.  title 의 속성 값이  html header 태그 내부에 써넣어진 바인딩 된다.

브라우저 재생되고 새로운 앱 제목이 보여진다. 

(터미널에 보니 알아서 번들링 하면 브라우저가 알아서 변경된 내용으로 보여진다. 변경된 코드를 수동 재배포 하거나 브라우저에서 새로고침이 없어도 갱신된 소스로 반영이된다. )


애플리케이션 스타일 추가

대부분의 애플리케이션은 애플리케이션에서 일관된 모양을 유지 하려고 합니다.

CLI은 일관된 모양을 유지하기 위해 빈 styles.css를 자동생성 했다.  앱의 전체 스타일을 여기에 배치 해라.


/* Application-wide Styles */

h1 {

  color: #369;

  font-family: Arial, Helvetica, sans-serif;

  font-size: 250%;

}

h2, h3 {

  color: #444;

  font-family: Arial, Helvetica, sans-serif;

  font-weight: lighter;

}

body {

  margin: 2em;

}

body, input[text], button {

  color: #888;

  font-family: Cambria, Georgia;

}

/* everywhere else */

* {

  font-family: Arial, Helvetica, sans-serif;

}

Summary

Angular CLI을 사용해서 초기 앱 구조를 생성한다.

Angular components 데이터 표시하는것을 배웠다.

앱제목을 표시할때 이중 중괄호를 사용해서 써넣는다

반응형
반응형

앵귤라 공식사이트에 있는 튜토리얼에 있는 내용을 직접 단계별로 해볼 계획이다.

앵귤라 공식사이트에 튜토리얼 -> https://angular.io/tutorial

튜토리얼은 총 8부분으로 나뉘어져 있다.

  1. Introduction 
  2. The Application Shell
  3. The Hero Editor
  4. Displaying a List
  5. Master/Detail Components
  6. Services
  7. Routing
  8. HTTP


1섹션은 소개, 2섹션은 애플리케이션 쉘, 3섹션은 영웅 수정, 4섹션은 목록 표시

5섹션은 주/상세 컴포넌트 6섹션은 서비스 7은 라우팅 8은 HTTP관련된 정보로 구분되어졌다.


첫번째 섹션은 만들 애플리케이션의 소개 내용이 담겨져 있다.

부족한 영어실력과 구글 번역기 돌리며 번역한 내용을 정리 해봤다.


튜토리얼은 Tour of Heroes 라는 제목으로 갖고 진행 한다.

이 튜토리얼은 앵귤라의 기본사항을 포함 하고 있다.


직원 채용 대행사 관리하는데 도움이 되는 앱을 튜토리얼 안에서 빌드 할수 있다.

이 기본 앱은  데이터 기반 애플리케이션에서 찾길 기대하는 많은 기능이 있다.

영웅 목록을 만들고 표시하고, 선택된 영웅의 세부사항을 수정하고 다르게 보이는 영웅적인 데이터를 다룹니다.


  • 튜토리얼이 끝날 무렵에 다음의 것을을 할수 있을 것이다.
  • 내장된 앵귤라 디랙티브들을 사용하여 요소를  보이거나  숨기고 영웅데이터를 목록으로 표시한다.
  • 앵귤라 콤포넌트를 만드는것은 영웅의 상세를 표시하고 영웅들의 배열을 표시한다.
  • 읽기전용 데이터는 한방햔 데이터 바인딩을 사용합니다.
  • 키보드를 누르는 거나 클릭하는거와 같은 사용자 이벤트에 컴포넌트 메소드를 바인드한다.
  • 사용자가 주 리스트에서 하나의 영웅을 선택하는것과 상세 보기에서 수정 할수 있다.
  • Format data with pipes.
  • 영웅들을 모으는 공유 서비스를 만듭니다.
  • 다른 뷰들 사이들과 과 그들의 콤포넌트들 사이에서 찾을때 라우팅을 사용합니다.


https://stackblitz.com/angular/ybbpegbnnlq

무엇을 만들지.

대시보드 라는 것으로 시작하고 더 영웅적인 영웅들을 볼수 있고

대시보드 에 두개 링크 ("Dashboard" and "Heroes" 로 구성 하여 화면이동

영웅을 클릭 하면 라우터는 "Hero Details" 을 열어 보여준후 그곳에서 영웅의 이름을 바꿀수 있다.

"Back"버튼을 클릭하는것은 대시보드로 돌아간다.상단위 링크들은 가진다. 메인뷰 중의 하나를. "Heroes"를 클릭하면  그 앱은 "Herose" 주목록이 표시된다

다른 영웅 이름을 클릭했을때, 읽기전용 작은 상세 아래에 그새로 선택된 것이 목록에 비친다.

상세보기 화면에서 선택된 영웅을 수정가능한 상세로 로 주입 한다네요;


만들려고 하는 애플리케이션의 설명을 이미지와 함께 설명하고 있다.

목록, 상세정보, 수정 등을 만든다는 내용인걸로 보인다. 



반응형
반응형

Angular 퀵스타트

테스트 환경 Window 10

Visual Studio Code 1.18.1

node -v v8.9.3

npm -v 5.5.1


https://angular.io/guide/quickstart

 Angular CLI 라는 명령라인 인터페이스를 통해 프로젝트로 생성하고 , 번드링, 배포, 파일추가 , 테스트 등을 수행할수 있는 도구랍니다.


1단계 : Angular CLI 설치

npm install -g @angular/cli

Angular CLI 설치한번만 하면 나중에 안해도 된다.


2단계 : 프로젝트 생성

ng new my-app

관련 페키지를 같이 설치하는데, 필요한건 인내심이라네요.

관려페이키를 아래와 같이 메세지가 나온다. 

139초니 2분 넘게 걸렸다.다.

added 1415 packages in 139.721s
Installed packages for tooling via npm.
Successfully initialized git.
Project 'inspinia' successfully created.


inspinia로 프로젝트를 생성했다.



3단계 : 서버 게재

cd my-app

ng serve --open

프로젝트 디렉토리로 이동하고 서버에 런처한다.

서버가 파일이 변경되면 지켜보고 있다가 알아서 리빌드 해준다네요.

옵션으로 --open 혹은 ( -o ) 로 하면 자동으로 http://localhost:4200/ 로 브로우저가 열립니다.


4단계 : 수정해보자

src/app/app.component.ts 파일을 찾아서

title = 'app';

title변수를 수정해보자.

바로 변하는 값을 브라우저에서 확인할 수 있다.


반응형
반응형

No tests found with test runner 'JUnit 5'.


tdd 테스트 소스를 위한 프로젝트 구성은

메이븐 기본을 따라서 하는걸로 해야겠다.

잘못 건드리면 저런 메시지 나와서 힘들다.


/src/main/java

/src/main/resources

/src/test/java

/src/test/resources




project -> configure -> convert to Maven 

반응형
반응형

@Test 어노테이션으로 테스트 메소드라는것을 선언한다.

@BeforeEach 테스트 실행전 작업


Test fixture 테스트를 반복적으로 수행할 수 있게 도와주고 매번 동일한 결과를 얻을 수 있게 도와주는 상태나 환경,  (test context)



java8 junit5로 작업중이다.

보고 있는책은 junit4다.

버전이 다르니 쓰이는어노테이션도 다르다.


Annotations

Features

JUnit 5

JUnit 4

Declares a test method@Test@Test
Denotes that the annotated method will be executed before all test methods  in the current class@BeforeAll@BeforeClass
Denotes that the annotated method will be executed after all test methods  in the current class@AfterAll@AfterClass
Denotes that the annotated method will be executed before each test method@BeforeEach@Before
Denotes that the annotated method will be executed after each test method@AfterEach@After
Disable a test method or a test class@Disable@Ignore
Denotes a method is a test factory for dynamic tests in JUnit 5@TestFactoryN/A
Denotes that the annotated class is a nested, non-static test class@NestedN/A
Declare tags for filtering tests@Tag@Category
Register custom extensions in JUnit 5@ExtendWithN/A
Repeated Tests in JUnit 5@RepeatedTestN/A

Assertions.

JUnit 4

JUnit 5

failfail
assertTrueassertTrue
assertThatN/A
assertSameassertSame
assertNullassertNull
assertNotSameassertNotSame
assertNotEqualsassertNotEquals
assertNotNullassertNotNull
assertFalseassertFalse
assertEqualsassertEquals
assertArrayEqualsassertArrayEquals
assertAll
assertThrows

출처 : https://howtoprogram.xyz/2016/08/10/junit-5-vs-junit-4/



현제 필요한 기능이 아니면 절대로 미리 만들지 말자.

여유가 된다면 변화에 민첩하게 대응가능하게 리팩토링 하자.

반응형

+ Recent posts