본문 바로가기

컴퓨터공학/Boot & Angular

Angular> 검색 기능

개발 순서

1. Spring boot에서 검색 메소드 생성

2. 검색을 위한 컴포넌트 생성

3. 검색을 위한 Angular route 생성

4. route에 데이터를 보내기 위한 검색 컴포넌트 수정

5. Product service를 통해 product를 검색하는 ProductListComponent 수정

6. Spring Boot에 URL을 요청하는 Product service 수정

 


Angular에서는 Event를 Event binding으로 감지한다. 다른 프레임워크에서는 Event handling이라고 한다. 

Event 종류는 

focus - 구성요소가 집중되었을 때

blur - 구성요소가 집중을 잃었을 때

keyup - 누른 키를 땔 때. keyup.enter

keydown - 버튼을 눌렀을 때

dbclick - 구성요소를 더블클릭했을 때

 

Event reference | MDN (mozilla.org)

 

Event reference | MDN

Events are fired to notify code of "interesting changes" that may affect code execution. These can arise from user interactions such as using a mouse or resizing a window, changes in the state of the underlying environment (e.g. low battery or media events

developer.mozilla.org

 

 

작동순서

1. 유저가 키워드를 검색창에 입력한다.

2. 검색 버튼을 누른다.

3. 검색 컴포넌트는 클릭 핸들러 이벤트를 갖고 있다.

4. 검색창 텍스트를 읽는다. 

5. 검색관련 route에 데이터를 보낸다.

6. ProductListComponent로 상품 리스트를 보여준다. 

 

 

검색 컴포넌트가 보내는 데이터에서 파라미터 값을 매핑하여

service를 사용해 데이터를 가져와 결과 데이터를 반환한다. 

product-list.component.ts이니 해당하는 HTML 영역인 router outlet에 결과값을 뿌린다. 

 

service 는 Boot에 보낼 전용 url을 만들어서 요청한다.

client response를 받아서 클래스 객체에 주입한다.

객체에 주입하는 원리는 response를 인터페이스를 사용하여 원하는 값만 맵핑하고

이걸 객체 클래스에 담아서 Observable로 객체 배열 반환.

REST API의 JSON 데이터를 product 객체 배열로 전환하는 것이다. 

클래스 객체 리스트를 반환하여 angular에게 전달한다.


 

1.

ProductRepository

select * from Product p where p.name like concat('%', :name ,'%')

같은 의미

 

검색완료

 

2. 3.

app.module.ts에서 route 추가하기 

 

검색컴포넌트 만들기

ng generate component components/search

 

4. 

이제 search route에 데이터를 보내기 위해 SearchComponent를 수정한다.

app.component.html 에서 search.component 태그를 집어넣는다. 

#myInput은 Template 참조 변수

keyup.enter 는 엔터키 이벤트를 듣고 있다는 것

doSearch는 Angular코드에서 이 이름의 메서드를 부른다는 것

 

 

search.compoent.ts에 router를 주입한다. 

router는 search route에 데이터를 보낸다. 그리고 ProductListComponent이 데이터를 다룬다. 

 

 

5.

 

 

search.component.ts에서 search route로 router를 이용해서 데이터를 보낸다. 

search route는 그걸 받아서 ProductListComponent로 간다. 

현재 받고 있는 route 경로에서 keyword 값 자리에 데이터가 있는지 없는지 확인한다.

있으면 service에 keyword를 입력하여 product 리스트를 가져온다.

 

6.

 

service에서는 url을 만들고 rest api에 요청한다.

response를 받아서 인터페이스에 주입하고 원하는 데이터만 받도록 맵핑한다.

이 배열을 product list component에 전달한다.

 

 

 

 


추가내용

결과값이 없을 경우 

ngIf의 내용은 if(product is null/undefined) or (products.length == 0) 뜻과 같다. 

?나 ! 이런 것들을 safe navigation operator라고 한다.

angular 공식 문서에서 보자~

Angular - Template syntax

 

Angular

 

angular.io