기본 콘텐츠로 건너뛰기

앵귤러 튜토리얼 (Angular tutorial) -14

앵귤러 튜토리얼 (Angular tutorial) -14

저번시간에는 web에서 메모리를 활용하여 데이터베이스의 효과를 보기위한 작업을 하였다.

이번시간에는 서비스를 조금 더 깔끔하게 수정해 보도록 하자.

이전 시간에는 메인컴포넌트에서 직접적으로 http모듈을 호출하여 데이터베이스에 접속하는 행위를 하였다.

"데이터베이스에 접속하는 행위" 라는 것은 메인 컴포넌트, 헤더 컴포넌트, 바디컴포넌트 등 다른 어떠한 컴포넌트에서도 공통적으로 사용되는 행위가 될 수 있다.

그러므로 공통적으로 사용되는 기능은 이전에 만들어둔 서비스로 분리하여 사용하도록 바꾸어 보자.

불필요한 코드를 먼저 제거하자. 메인컴포넌트에서 불필요한 코드는 싹 제거한다.

import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'dashboard'; constructor(){ } private showType : any; getEventFromHead (event){ this.showType = event; } }

그러고보니 a일 경우에는 사용자, b일 경우에는 게시판이 나오도록 값을 정하였었다. (헤더에서 클릭할 때)

마찬가지로 해당 데이터도 공통으로 사용되니 아에 분리를 시켜보자.

기존에 모듈에서 사용했던 ShareData의 내용을 수정하자.

import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; import { HeadComponent } from './head/head.component'; import { BodyComponent } from './body/body.component'; import { ShareService } from './share.service'; //해당 서비스 임포트 import { HttpClientModule } from '@angular/common/http'; //http import {WebDbService} from './web-db.service'; //웹DB import {InMemoryWebApiModule} from 'angular-in-memory-web-api'; //DB구현 모듈 const ShareData = [ {type :'A', url : '/test/user'}, //type이 A이면 사용자 값url {type :'B', url : '/test/dash'} //type이 B이면 게시판 값 url ]; @NgModule({ declarations: [ AppComponent, HeadComponent, BodyComponent ], imports: [ BrowserModule, InMemoryWebApiModule.forRoot(WebDbService,{delay:500,put204:false}), //DB구현 모듈 추가 HttpClientModule //HTTP 연결 ], providers: [{provide: 'alias',useValue:ShareData}, ShareService], bootstrap: [AppComponent] }) export class AppModule { }

type이 A이면 사용자, B이면 게시글이 나오도록 하기 위해서 ShareData 상수의 내용을 배열형태로 바꾸었다.

web-db 역할을 하는 서비스에 기본적으로 글이 나오도록 아래처럼 수정하여 주자.

import { Injectable } from '@angular/core'; import {InMemoryDbService} from 'angular-in-memory-web-api'; @Injectable({ providedIn: 'root' }) export class WebDbService implements InMemoryDbService{ private _database : any; //데이터베이스 constructor() { } createDb(){ //상속받아 구현 this._database = {}; this._database['user'] = [ //기본 데이터1 {name:'관리자',date:'2019-01-20',id:'root'}, {name:'고급사용자',date:'2019-06-18',id:'admin'}, {name:'일반사용자',date:'2019-05-04',id:'user'} ]; this._database['dash'] = [//기본 데이터2 {title:'title - 1', desc : 'description', date:'2019-05-11'}, {title:'title - 2', desc : 'description', date:'2019-06-20'}, ]; return this._database; } }

http 요청을 수행해야될 서비스를 이제 수정해볼 차레이다.

간단하게 가져오는 메소드, 등록하는 메소드를 만들어보자.

주소와 파라미터를 받는 메소드를 share.service에 추가한다.

import { Injectable } from '@angular/core'; import { HttpClient, HttpParams } from '@angular/common/http'; @Injectable({ providedIn: 'root' }) export class ShareService { public shareValue : number = 1004; //변수 private HTTP : HttpClient; constructor(http : HttpClient) { this.HTTP = http; } getData(url, param){ //가져오는 함수 this.HTTP.get(url, param).subscribe((res)=>{ console.log(res); }); } setData(url, param){ //등록하는 함수 this.HTTP.put(url, param).subscribe((res)=>{ console.log(res); }); } }

일단 콘솔로 찍게만 하였다.

그리고 이벤트를 받는 바디컴포넌트를 최종적으로 수정하자.

import { Component, OnInit, Inject } from '@angular/core'; import { Input } from '@angular/core'; import { ShareService } from '../share.service'; @Component({ selector: 'app-body', templateUrl: './body.component.html', styleUrls: ['./body.component.css'] }) export class BodyComponent implements OnInit { private code : any; private service : ShareService; constructor(@Inject('alias') alias, serve : ShareService ) { //생성자로 받기 this.code = alias; //모듈에서 넘어온 배열값 this.service = serve; } @Input() set getShowType(arg : any){ //set 문법 this.code.forEach( item => { //반복문 if(item.type == arg){ //type값이 같다면.. this.service.getData(item.url , {}); } }); } ngOnInit() { } }

버튼을 클릭할 때마다 콘솔로 데이터가 잘 나옴을 확인 할 수 있다.

그렇다면 데이터를 화면에 표출을 하고싶은데..subscribe에서 데이터를 어떻게 가져와서 표현해야 될까..?

share.service를 아래처럼 바꾸어보자.

import { Injectable } from '@angular/core'; import { HttpClient, HttpParams } from '@angular/common/http'; @Injectable({ providedIn: 'root' }) export class ShareService { public shareValue : number = 1004; //변수 private HTTP : HttpClient; constructor(http : HttpClient) { this.HTTP = http; } getData(url, param, callback){ //가져오는 함수 this.HTTP.get(url, param).subscribe((res)=>{ console.log(res); callback(res); }); } setData(url, param, callback){ //등록하는 함수 this.HTTP.put(url, param).subscribe((res)=>{ console.log(res); callback(res); }); } }

callback이라는 람다가 생겼다. callback은 자바스크립트로 비교하자면 함수형태 function(){}값을 넣어준 것과 동일한 행위이다.

자바스크립트로 표현하면 아래와 같은 내용 이다.

function abcd(aaa, todo){ //todo는 함수abcd가 실행할 행위 이다. var number = 10; aaa = aaa+ 10; todo(aaa); } abcd(10, function(result){ //콜백 행위 console.log(result); });

콜백행위, 즉 url을 호출한 행위가 정의 되었으니 이제 바디컴포넌트를 다시 수정하자.

import { Component, OnInit, Inject } from '@angular/core'; import { Input } from '@angular/core'; import { ShareService } from '../share.service'; @Component({ selector: 'app-body', templateUrl: './body.component.html', styleUrls: ['./body.component.css'] }) export class BodyComponent implements OnInit { private code : any; private service : ShareService; constructor(@Inject('alias') alias, serve : ShareService ) { //생성자로 받기 this.code = alias; //모듈에서 넘어온 배열값 this.service = serve; } private list : any; //user 데이터를 그려줄 리스트 private list2 : any; //dash 데이터를 그려줄 리스트 @Input() set getShowType(arg : any){ //set 문법 this.code.forEach( (item, index) => { //반복문, index 0은 A값, 1은 B값이다. if(item.type == arg){ //type값이 같다면.. this.service.getData(item.url , {}, (result)=>{ //람다를 추가하여 데이터를 받자. if(index == 0){ //A값이면 this.list = result; this.list2 = null; } else { //B값이면 this.list = null; this.list2 = result; } }); } }); } ngOnInit() { } }

데이터를 표현하기위해 list와 list2라는 변수를 선언하였다.

바디컴포넌트의 html파일을 앞선시간에 살펴본 ngFor를 통해서 출력하면 제법 그럴싸하게 데이터가 나온다.

바디컴포넌트의 html파일을 수정하자.

{{item.id}} {{item.name}} {{item.date}} {{item.title}} {{item.desc}} {{item.date}}

상단 헤더의 버튼을 누르면 데이터가 원하는데로 잘 표출됨을 알 수 있다.

처음 실행 모습 유저버튼 클릭 대쉬보드 버튼 클릭

여기까지 잘 따라왔다면 앵귤러의 기초중의 기초는 거의 다 한것으로 볼 수 있다.

1. 컴포넌트의 의미와 관계

2. 모듈의 의미와 관계

3. 서비스의 의미와 관계(공통으로 사용되는)

이제 남은 기능은 헤더컴포넌트에서 아직 공통으로 사용되는 변수인 ShareData를 활용하여 헤더의 html을 동적으로 바꾸는 행위 1개와, share서비스에 있는 setData를 사용하는것 1개가 남았다.

해당 2가지의 기능은 이제 직접 복습 또는 구글링을 통해서 구현해보도록 하자.

다음시간에는 subscribe라는 함수의 의미와 역할, 기능이 무엇인지 알아보도록하자.

src.zip 0.01MB

from http://lts0606.tistory.com/131 by ccl(A) rewrite - 2020-03-06 04:20:32

댓글

이 블로그의 인기 게시물

[django] django rest framework 로그인 과정 | 장고 로그인 | 인증...

[django] django rest framework 로그인 과정 | 장고 로그인 | 인증... django 는 기능이 참 너무 많다 ^^; 지금은 서버는 django로, 프론트는 angular를 붙여서 간단한 웹을 만들어 보려고 한다. 웹 만들때 항상 회원가입/로그인 기능은 맨 앞에 구현한다. 어떻게 구현하면 좋을까... 찾아보다가 이 기능을 구현할 수 있는 방법이 너무 많아서 정보를 찾기 더 어려웠다. 일단 나는 django에서 django rest framework라는 것을 사용해서 API를 만드려고 한다. 순수 django 튜토리얼에는 바로 template 랑 연결해서 설명하는 부분이 많았다. 나는 그냥 API 만 만들고 싶다고!! 그래서 찾은 것이 django REST framework. https://www.django-rest-framework.org/api-guide/authentication django REST framework 설치 using pip pip install djangorestframework settings.py INSTALLED APPS 에 추가해야함 INSTALLED_APPS = [ ... 'rest_framework', ] django REST framework 에서도 인증 관련해서 제공하는 것이 1개가 아닌 여러 개다. 나는 그중에 TokenAuthentication을 이용해서 로그인을 구현해 보려고 한다. TokenAuthentication Token authentication is appropriate for client-server setups, such as native desktop and mobile clients. 이렇게 나와있어서 내가 하려는 것과 일치해서 이걸로 결정 ~ 솔직히 처음 로그인을 구현하려고 하면 도대체 그 과정이 어떻게 되는지 모를 수 도 있다. 나는 쉽게 정리하면 아래와 같은 과정이라고 생각한다. 로그인 로그아웃...

(주)레터플라이 채용 정보: 프로그래밍을 생각하면 가슴이 뛰는 개발자...

(주)레터플라이 채용 정보: 프로그래밍을 생각하면 가슴이 뛰는 개발자... Angular.js, Python, MySQL 중 한 가지 언어에 뛰어나신 분도 좋고 개발 업무 전반적으로 센스가 있으신 분도 환영합니다. 맡은 업무를 성실하게 수행해 나갈 수 있는 책임감과 태도를 갖고계신 분, 그리고 항상 새로운 방법론에 도전하고 포기를 모르는 분일수록 저희와 더욱 잘 맞을 것 같습니다. Angular.js, Python, MySQL 중 한 가지 언어에 뛰어나신 분도 좋고 개발 업무 전반적으로 센스가 있으신 분도 환영합니다. 팀 내 뛰어난 풀스택 개발자분들이 Angular.js, Python, MySQL 모두 작업 가능하시니 오셔서 함께 배우며 즐겁게 작업하시면 됩니다. 맡은 업무를 성실하게 수행해 나갈 수 있는 책임감과 태도를 갖고계신 분, 그리고 항상 새로운 방법론에 도전하고 포기를 모르는 분일수록 저희와 더욱 잘 맞을 것 같습니다. 개발 업무: 레터플라이의 핵심 기능인 편지, 사진을 제작하는 레터에디터, 포토에디터 개발. 이 기능들은 "모바일 웹을 통한 출력제품 생산 자동화 기술"(특허 출원 준비중)로서 레터플라이에서 자체개발했습니다. 근무 지역: 광화문역 5번출구 바로 앞 근무 환경: 책임과 존중을 중요시하는 수평적인 분위기, 도전적이며 서로에게 배우는 문화 근무 시간: 10-19시, 출근시간 자유 지정. 급여: 연봉/스톡옵션 협의 지원 방법: 팀 지원하기 더 많은 내용은 더 많은 내용은 더팀스 에서 확인하세요! from http://theteams.tistory.com/721 by ccl(A) rewrite - 2020-03-20 09:20:18

jqxGrid 정렬, 필터 메뉴 숨기기

jqxGrid 정렬, 필터 메뉴 숨기기 How I can remove filter to particular grid column - Angular, Vue, React, Web Components, Javascript, HTML5 Widgets Hi, I tried that it's working. I set properties to those columns as sortable: false, filterable: false. but when I clicked on the column one drop down is appearing with options "sort ascending", "sort descending", "remove sort" and those are all in disable www.jqwidgets.com from http://devesim.tistory.com/90 by ccl(A) rewrite - 2020-03-11 04:20:29