2 UI  에 이어서 마저 작성을한다



UI 에서 입력한값을 mongoDB로 입력할수있게해주려한다


2장에서 작성한 

collect.component.ts 추가 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
   addinfo(
    email:string,
    name:string,
    hashtag:string,
    frcal:string,
    tocal:string,
     twitter:string,
    ){
      
      
       var query = {
                         "hashtag" : hashtag,
                          "email" :  email,
                          "frcal" : frcal,
                          "tocal" : tocal,
                          "twitter" : twitter,
                         "name"    : name
       }
       
        var headers = new Headers(); 
        headers.append('Content-Type''application/json')
        this.http.post('http://localhost:4100/dbUserinsert',query,{headers: headers}).subscribe((res) => {
        
    );
cs


server.js 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
var express = require('express');
var request = require('request');
var bodyParser = require('body-parser');
var cors = require('cors');
var functions = require('./functions');
var dbsearch = require('./dbsearch');
var app = express();
var Scheduler = require('nschedule');
var config = require('./config');
var async = require('async');
 
 
 
 
           
         app.use(express.static(__dirname));
        app.post('/dbUserinsert',dbsearch.Userinsert);  //입력받은값 디비 저장
        app.listen(process.env.PORT || 4100);
        console.log("Server up on port 4100");
cs

MongoDB 설치

1
2
3
npm install mongojs -
//MongoDB 설치
 
cs


dbsearch.js 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
var searchfunctions = require('./functions')
var mongojs = require('mongojs');
var db = mongojs('mongodb://''@''.mlab.com:63406/');
 
functions = {
 
 Userinsert : (req,res) => {
    var req = req.body;
    console.log(req)
     db.collect.save(req, function(err, result){
                if(err){
                    res.send(err); 
                    console.log(err);
                } else {
                    res.json(result);
                    console.log(result);
                }
            });
        
    }}  
cs




작성한 코드를 실행하게 되면


입력받은 값을  query 변수에 입력하고 JSON 으로 보내게 된다 


서버에서는 호출 된 URL http://localhost:4100/dbUserinsert app.post 시켜서  dbsearch.js 에 있는


Userinsert 함수를 실행시켜주게 된다 


완성이되면  이전페이지에서 보게된거처럼 그리드에 바인딩이 되어진다 




#입력된값을 DB 에 저장시키는 코드 까지 작성을 완료 했다

다음페이지에서는 일정시간마다 instagram,twitter 데이터를 크롤링 하는 스케쥴링을 포스팅할예정이다 




WRITTEN BY
내가달이다

,



마저 작성한다


첫번째  등록버튼을 클릭할때 위의 메뉴가 나오게 하고싶다

두번째  수집기간을 달력버튼이 말고 텍스트박스를 클릭할때 달력을 표시하게해주고싶다

세번째 수집된내용을 DB 에 저장시키고 목록을 그리드에 바인딩시켜준다

네번째 바인딩된 그리드 클릭후 엑셀출력 버튼을 클릭하면 수집된내용을 엑셀로 출력시켜준다



#첫번째

collect.component.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
<div class="row">
  <div class="large-6 columns">
    <button (click)="changeState('add')" class="btn btn-primary">신규등록</button>
  </div>  
</div>
<p></p>
<div *ngIf="appState == 'add'" class="row">
    <form class="form-horizontal"  [formGroup]="VailidateForm" (submit)="addinfo(
        email.value,
        name.value,
        hashtag.value,
        frcal.value,
        tocal.value,
        twitter.value
        )">
  <fieldset>
    <legend>신규 등록</legend>
    <div class="form-group" >
      <label for="inputEmail" class="col-md-1 control-label">이메일</label>
      <div class="col-md-5" [ngClass]="{'has-error':!VailidateForm.controls['email'].valid && VailidateForm.controls['email'].touched}">
        <input type="text" class="form-control" placeholder="@naver.com" #email [formControl]="VailidateForm.controls['email']" >
        <div *ngIf="VailidateForm.controls['email'].hasError('required') && VailidateForm.controls['email'].touched" class="alert alert-danger">이메일을 입력해주세요</div>
      </div>
    </div>
    <div class="form-group">
      <div class="col-md-1">
          <input type="submit"  class="btn btn-primary" value="등록" [disabled]="!VailidateForm.valid">
      </div>
        <div class="col-md-1">
          <button  class="btn btn-primary" (click) ="changeState('appState','default')" >
            취소
          </button>
         </div>
    </div>
  </fieldset>
</form>
</div>
<div style="width: 100%;">
    <ag-grid-ng2 #agGrid style="width: 100%; height: 200px;" class="ag-fresh"
                 [gridOptions]="gridOptions" (rowClicked)='onRowClicked($event)'
                 >   
    </ag-grid-ng2>
</div>
 
 
 
cs

collect.component.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import { Component,Input,OnInit,Injectable,OnDestroy,ViewChild } from '@angular/core';
import {Collect}  from '../collect';
import {GridOptions} from 'ag-grid/main';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
 
declare  var $:any;
 
 
@Component({
    moduleId:module.id,
    selector: 'collect',
    templateUrl: 'collect.component.html',
     styleUrls: ['collect.component.css']
 
})
@Injectable()
export class CollectComponent implements OnInit{
 
 VailidateForm : FormGroup;
 
 constructor(private http:Http,fb: FormBuilder){ 
 
        this.VailidateForm = fb.group({
        'email' : [null, Validators.required],
        'id' : [null, Validators.required],
        'hashtag' : [null , Validators.required],
        'date' : [null , Validators.required]
      })
 
      console.log(this.VailidateForm);
      this.VailidateForm.valueChanges.subscribe( (form: any) => {
        console.log('form changed to:'form);
      }
    );
cs

위 화면을 작성한 코드 예제이다


돌아가는 사이클은 신규등록을 클릭할시 밑에 form 들을 보여주게한다


위 코드에서 눈여겨 볼만한것은 *ngIf , [ngClass] ,[formControl] 이다


1.*ngIf


1
2
3
4
5
6
7
 
 
<div *ngIf="appState == 'add'" class="row">
    <!-- 변수의 값이 appState와 일치할 때 이 태그가보여진다 .-->
</div>
 
 
cs

2~3.[ngClass],[formControl]

1
2
3
4
5
[ngClass]="{'has-error':!VailidateForm.controls['email'].valid && VailidateForm.controls['email'].touched}"
//email 폼 값이 비어있거나 클릭이 되었을경우 발생한다
 
[formControl]="VailidateForm.controls['email']"
//form컨트롤값 지정
cs



collect.component.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
constructor(private http:Http,fb: FormBuilder){ 
 
        this.VailidateForm = fb.group({
        'email' : [null, Validators.required],
        'id' : [null, Validators.required],
        'hashtag' : [null , Validators.required],
        'date' : [null , Validators.required]
      })
 
      console.log(this.VailidateForm);
      this.VailidateForm.valueChanges.subscribe( (form: any) => {
        console.log('form changed to:'form);
      }
cs


코드를 살펴보자 vaildateForm 값을 넣어주고 


vaildateform 값이 변할때마다 log 를 찍어주도록하였다 





코드를 실행해보면





이러한 화면을 간단하게 만들어보았다


WRITTEN BY
내가달이다

,

이번 개인프로젝트를 웹으로 새로 공부해볼겸 해서 MEAN stack 을 이용해서 간단하게 만들어볼까한다 



우선 MEAN stack 이란 





자세한 설명은 생략 하겠습니다 구글에 검색해보면 무궁무진하게 나와서....


대략적인 구상은 


angular2 를 이용해 원하는 키워드입력을 받아 수집하는 화면UI 를 작성하고 


node,express를 이용해 mongodb 에 저장하는  그림으로 갈예정이다






#Angular2


가장 기본적인 Angular2 의 Hello Angular2 을 찍어볼까한다  hello world가아니라니....


app.component.ts

1
2
3
4
5
6
7
import { Component } from '@angular/core';
@Component({
  selector: 'my-app',
  template: `<h1>Hello {{name}}</h1>`
})
export class AppComponent { name = 'Angular'; }
 
cs


index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<!DOCTYPE html>
<html>
  <head>
    <title>Hello Angular</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
      body {color:#369;font-family: Arial,Helvetica,sans-serif;}
    </style>
 
    <!-- Polyfills for older browsers -->
    <script src="https://unpkg.com/core-js/client/shim.min.js"></script>
 
    <script src="https://unpkg.com/zone.js@0.6.25?main=browser"></script>
    <script src="https://unpkg.com/reflect-metadata@0.1.8"></script>
    <script src="https://unpkg.com/systemjs@0.19.39/dist/system.src.js"></script>
 
    <script> window.autoBootstrap = true</script>
 
    <script src="https://cdn.rawgit.com/angular/angular.io/b3c65a9/public/docs/_examples/_boilerplate/systemjs.config.web.js"></script>
    <script>
      System.import('app').catch(function(err){ console.error(err); });
    </script>
  </head>
 
  <body>
    <my-app>Loading AppComponent content here ...</my-app>
  </body>
 
</html>
 
cs


참조 : https://angular.io/docs/ts/latest/quickstart.html


간단한 Hello Angular 를 찍어보는 예제 이다 


공부를 하다보니 특이하게 동작을 하더라 


app.component.ts  

 

안의 내용을 확인해보면  import component 를 통해 componenet 를 불러오고 


1
2
3
4
5
6
 
@Component({
  selector: 'my-app',
  template: `<h1>Hello {{name}}</h1>`
})
 
cs


@Component를 살펴보면 


selector : 'my-app' 이 보이고 template 내용이보였다


처음에 'my-app' 은 또 어서나온거야 하고 당황했는데  찾아보니 


 index.html 


1
2
3
4
 
  <body>
    <my-app>Loading AppComponent content here ...</my-app>
  </body>
cs


이쪽에 있더라 


대강 눈치밥으로 돌아가는 것을 보니


index.html 의 <my-app> 부분이 app.component.ts 를 호출하는것으로 보인다


실행결과는 http://plnkr.co/edit/ZYvdJiYxwhdZMx8MmJYj?p=preview&open=app%2Fapp.component.ts 






다음포스팅은 기능의 한부분인 페이지를만들어볼 예정이다


대략적인 구성은 



사용자가 원하는 키워드 입력시 수집내용을 입력하고 등록을 누르고 그후 목록을 보여주고 엑셀로 출력까지 해주는  페이지를 만드려한다


WRITTEN BY
내가달이다

,

평소에 c# 윈폼만 다뤄보다가 개인프로젝트로 웹어플리케이션을 공부하려고 공부 & 작업일지겸 작성한다



스타트업 에서 주로사용되는  MEAN stack 을 활용해 만들어볼계획이다



기회가 된다면 파이썬으로도 해볼생각이다




WRITTEN BY
내가달이다

,