[Angular2] Angular 2 Host in Apache Server


一般都用Angular CLI的 ng server去host

但突然想要用 Apache


1. ng new YourProj



2.  set build/output directory(option)

// in angular-cli.json 
// outDir 可以設定build/output的資料夾,預設是dist

"apps": [
    {
      "root": "src",
      "outDir": "dist",  
      "assets": [
        "assets",
        "favicon.ico"
      ],
      "index": "index.html",
      "main": "main.ts",
      "test": "test.ts",
      "tsconfig": "tsconfig.json",
      "prefix": "app",
      "mobile": false,
      "styles": [
        "styles.css"
      ],
      "scripts": [],
      "environments": {
        "source": "environments/environment.ts",
        "dev": "environments/environment.ts",
        "prod": "environments/environment.prod.ts"
      }
    }
  ],



3.use relative path
// in index.html
//  base href="/"  -> base href="./"  
base href="./"     





4.ng build --prod
bulid完就會出現dist資料夾
然後把dist資料夾移到apache的路徑下就ok了









[Anguler2] routing 用法

youtube影片可以參考:https://youtu.be/Uvj_7ZMrHmg


1.新增 app.router.ts
import { ModuleWithProviders } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';


import { AppComponent } from './app.component';
import { AboutComponent } from './about/about.component';
import { ServicesComponent } from './services/services.component';



// setting router path
export const router: Routes = [
     {path: '', redirectTo: 'services', pathMatch: 'full' },  //redirect to service
     {path: 'about', component: AboutComponent },
     {path: 'services', component: ServicesComponent },
];

// generate router module
export const routes: ModuleWithProviders = RouterModule.forRoot(router);




2.app.module.ts 要import routes
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import {routes} from './app.router'; //import 

import { AppComponent } from './app.component';
import { AboutComponent } from './about/about.component';
import { ServicesComponent } from './services/services.component';




@NgModule({
  declarations: [
    AppComponent,
    AboutComponent,
    ServicesComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    routes //import 
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }



3.app.component.html 設定routerLink & router-outlet
//router-outlet就是所對應的component表現的地方


 
  •         Services
     
     
        <router-outlet></router-outlet>

    [Angular2] service with Http Error Catch 用法

    當http 抓不到資料時拋出錯誤
    github

    1. import 
    /* employee.service.ts */
    ------------------------------------

    import { Injectable } from '@angular/core';
    import { Http, Headers, Response } from '@angular/http'; //import Http, Headers , Response
    import {Observable} from 'rxjs/Observable';  //import Observable
    import 'rxjs/add/operator/map'; //import rxjs map
    import 'rxjs/add/operator/catch'; //import rxjs catch
    import 'rxjs/add/Observable/throw';

    @Injectable()
    export class EmployeeService {

        private _url: string = "../apidata/employeeData.json";

        constructor(private _http: Http) {}

        getEmployees(){ 
            return this._http.get(this._url)
                    .map(res => res.json())
                    .catch(this._errorHandler);  // catch error handler
        } 

        _errorHandler(err: Response){
            console.error(err);
            return Observable.throw(err || "Server Error");
        }

    }



    2.
    /* employee-list.component.ts */
    -------------------------------------------------
    import { Component, OnInit } from '@angular/core';
    import { EmployeeService } from '../employee.service';


    @Component({
      selector: 'app-employee-list',
      templateUrl: './employee-list.component.html',
      styleUrls: ['./employee-list.component.css']
    })
    export class EmployeeListComponent implements OnInit {
        employees = [];
        errorMsg: string;

        constructor(private _empService: EmployeeService) { }

        ngOnInit() {
            // this.employees = this._empService.getEmployees();
            this._empService.getEmployees()
                .subscribe(resEmpData => this.employees = resEmpData,
                           resEmpError => this.errorMsg = resEmpError);
        }


    }


    [Angular2] service via Http Rxjs 用法

    在 service 用http 去要資料(json)

    然後給component 用


    1. get data via Http
    /* employee.service.ts*/
    ------------------------------------
    import { Injectable } from '@angular/core';
    import { Http, Headers } from '@angular/http'; //import Http, Headers 
    import 'rxjs/add/operator/map'; //import rxjs

    @Injectable()
    export class EmployeeService {

        private _url: string = "../apidata/employeeData.json";

        constructor(private _http: Http) {}

        getEmployees(){ 
            return this._http.get(this._url)
                    .map(res => res.json());
        } 

    }



    2.subscribe
    /* employee-list.component.ts*/
    -----------------------------------------------
    import { Component, OnInit } from '@angular/core';
    import { EmployeeService } from '../employee.service';


    @Component({
      selector: 'app-employee-list',
      templateUrl: './employee-list.component.html',
      styleUrls: ['./employee-list.component.css']
    })

    export class EmployeeListComponent implements OnInit {
        employees = [];

        constructor(private _empService: EmployeeService) { }

        ngOnInit() { 
            this._empService.getEmployees()
                .subscribe(resEmpData => this.employees = resEmpData);
        }


    }


    [Angular2] Output 用法

    從inside component 發送一個值到App component


    1.import EventEmitter, Output
       emitSpot 就像是發射台,將東西發射出去

    /* inside.component.ts */
    ------------------------------------
    import { Component, OnInit, EventEmitter, Output } from '@angular/core';

    @Component({
      selector: 'app-inside',
      templateUrl: './inside.component.html',
      styleUrls: ['./inside.component.css']
    })

    export class InsideComponent implements OnInit {

      @Output()
      emitSpot = new EventEmitter;

      sendTextToAppComp(val: string){
          console.log("outputText2App func working");
          console.log(val);
          this.emitSpot.emit(val)
      }

      constructor() { }

      ngOnInit() {
      }

    }









    2. html 就簡單按 click button 後呼叫sendTextToAppComp()將 input value 送到App Comp
    /* inside.component.html */
    ----------------------------------------




    3.

    /* app.component.html */
    ----------------------------------------


      {{title}}

    {{AppText}}



    emitSpot)="OutputTextFromInsideComp($event)">



    4.
    /* app.component.ts */
    ----------------------------------------
    import { Component } from '@angular/core';

    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })

    export class AppComponent {
      title = 'app works!';
      public AppText = '';

      OutputTextFromInsideComp($event){
          console.log("OutputTextFromInsideComp Working");
          console.log("event: :"+$event);
          this.AppText = $event;
      }

    }


    流程大概就是
    sendTextToAppComp() -> emitSpot.emit(val) -> (emitSpot) -> OutputTextFromInsideComp($event) -> this.AppText = $event;









    [Angular2] Input 用法

    將 App component 的值 input 到 inside component 用

    也就是 inside comp 需要吃一個值 從 App comp

    github


    1. import input, 設定input 的變數

    /* inside.component.ts*/
    ------------------------------------
    import { Component, OnInit ,Input} from '@angular/core';   //import Input

    @Component({
      selector: 'app-inside',
      templateUrl: './inside.component.html',
      styleUrls: ['./inside.component.css']
    })

    export class InsideComponent implements OnInit {

      @Input()
      public inputTextFromAppComp='';

      constructor() { }

      ngOnInit() {
      }

    }



    2.  html 部分就簡單直接print

    /* inside.component.html*/
    ------------------------------------
    input text from AppComp:

    {{

    inputTextFromAppComp}}



    3. 

    /* app.component.ts*/
    ------------------------------------
    import { Component } from '@angular/core';

    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })

    export class AppComponent {
      title = 'app works!';
      public appText = "string in app comp "

    }





    4.在App comp的appText 傳給 在inside Comp 的 inputTextFromAppComp

    /* app.component.html*/
    ------------------------------------

    inputTextFromAppComp]="appText" >










    [Angular2] service 用法

    1.先用 "ng g service EmployeeService"  create service

    create src/app/employee-service.service.spec.ts
    create src/app/employee-service.service.ts





    2. 在service裡面寫 getEmployees() function
    /* employee-service.service.ts*/ 
    ----------------------------------------------
    import { Injectable } from '@angular/core';

    @Injectable()
    export class EmployeeService {

        employessData = [
            {"id":1, "name":"name_1", "age":11},
            {"id":2, "name":"name_2", "age":12},
            {"id":3, "name":"name_3", "age":13}
        ];


       
    // getEmployees() in service

        getEmployees(){
            return this.employessData;
        }

      constructor() { }


    }






    3. import service 
    /* app.component.ts*/ 
    ----------------------------------------------
    import { Component } from '@angular/core';
    import { EmployeeService } from "./employee.service"  //import service

    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css'], 
      providers: [EmployeeService]   // add providers
    })

    export class AppComponent {
      title = 'app works!';
    }






    /* employee-list.component.ts*/ 
    ----------------------------------------------

    import { Component, OnInit } from '@angular/core';
    import { EmployeeService } from '../employee.service';  //import service



    @Component({
      selector: 'app-employee-list',
      templateUrl: './employee-list.component.html',
      styleUrls: ['./employee-list.component.css']
    })

    export class EmployeeListComponent implements OnInit {
        employees = [];

        constructor(private _empService: EmployeeService) { }

        ngOnInit() {
            this.employees = this._empService.getEmployees();//get data via emp service
        }

    }



    /* employee-list.component.html*/ 
    ----------------------------------------------

    • {{item.name}}





    • result:






      [Angular2] npm install 錯誤 Error: Cannot find module 'minimatch' 解法 (Mac)



      解法可參考https://github.com/npm/npm/issues/10434 Keyamoon的回覆

      基本上就是把/usr/local/lib/node_modules/npm 整個資料夾刪除

      然後再去https://nodejs.org/en/download/ 下載重新安裝一次 Node.js

      就可以順利npm install Angular 2 package


      install Samba in Ubuntu

      #安裝samba
      sudo apt-get install samba

      #修改 samba 設定
      sudo vim /etc/samba/smb.conf

      #在smb.conf 最後加

      [pi]
        comment=pi's home
        path=/home
        read only=no
        guest ok=no
        browseable=yes
        create mask=0755
        directory mask=0755


      #重啟服務
      sudo service smbd restart



      #設定帳號密碼 
      sudo smbpasswd -a pi



      smb://xxx.xxx.xxx.xxx
      就可以進去囉

      [Python] fix string 亂碼 codec can't decode

      在接資料時,剛好也接到 Serial 在拋query的數據訊號

      剛好是亂碼

      python 在轉 unicode 時就爆錯惹


      UnicodeDecodeError: 'ascii' codec can't decode byte 0xc0 in position

      這時大決直接 ignore

      str = str.decode('utf-8', 'ignore')


      如果還不給力就要使用regex惹

      先 import re

      replacedStr = re.sub('[^A-Za-z0-9_":\{\}]+', "", str)


      [^A-Za-z0-9_":\{\}] 排除大小寫字母、數字 、底線 、"號、大括弧{}

      json大概就用到這些,除了把上面之外的都用取代掉

      replacedStr = replacedStr.replace('}"','},"') //補上逗點用的


      收工





      [Arduino] serial communication using PySerial (Mac)

      1.安裝Pyserial

      首先到https://pypi.python.org/pypi/pyserial 下載tar.gz檔

      tar -xzf pyserial-3.1.1.tar.gz

      cd pyserial-3.1.1

      sudo python setup.py install


      [PHP] Firebase in PHP (Mac)


      [PHP] 安裝Composer for Mac


      安裝composer



      //in Terminal

      curl -sS https://getcomposer.org/installer | php
      php composer.phar 
      mv composer.phar /usr/local/bin/composer
      composer

      [Raspberry Pi] 接收Arduino的資料

      影片可參考


      //安裝python
      sudo apt-get install python


      //安裝moreutils
      sudo apt-gey install moreutils

      //安裝grabserial
      wget https://raw.githubusercontent.com/tbird20d/grabserial/master/grabserial grabserial


      //先lsusb一次,然後插上Arduino再lsusb看有沒有抓到Arduino
      lsusb


      //看Arduino抓到的裝置代號,ttyUSB0 或是 ttyACM0
      ls /dev/tty*


      //編輯grabserial 參數
      nano grabserial


      //in grabserial file
      sd.port="/dev/ttyACM0"   // 如果你ls /dev/tty*是 ttyUSB0 就改sd.port="/dev/ttyUSB0"
      sd.baudrate=9600


      然後在Arduino隨便寫個可以拋資料的

      //顯示Arduino傳過來的Data
      python grabserial


      //把Arduino傳過來的Data存在a.txt ,Terminal上不會顯示
      python grabserial > a.txt




      [Raspberry Pi] 開機後自動執行python

      影片可參考






      cd /home/pi                  //cd  到pi目錄


      sudo nano test.py        //隨便打個print測試


      sudo nano .bashrc      //編輯.bashrc

      python test.py              //在.bashrc最後一行新增

      [Arduino] RDIF 讀取Mifare RFID卡的UID識別碼


      [Arduino] Modbus RTU via RS485(MAX485 IC)

      工作需要用Modbus RTU去跟機器通訊

      卡關幾天後終於成功了...

      不懂Modbus的可以參考這裡http://www.xuan.idv.tw/wordpress/?p=1705

      [Arduono] LM35 with LCD display


      [Arduino] RS485 serial port connect via MAX485 (Mac)


      [Raspberry] 安裝系統,設定,SSH,VNC,接觸控螢幕


      [Arduino] LM35 溫度感應sensor



      Google Drive Direct Download Link Generator



      header 滾動至上方fixed

      單純筆記用@@
      白色滾動到上方時position:fixed


      [iOS] UITextField 隱藏 keyboard

      假設現在有兩個 UITextField 打完字按視窗要把keyboard縮下去

      要先在class 加上 UITextFieldDelegate

      後面設定請參考



      [iOS] Alamofire 安裝

      如果沒有 CocoPods 請先安裝

      STEP1.在Xcode開一個project  然後 關掉Xcode

      STEP2. 利用 terminal cd 到剛剛的project 資料夾

      STPE3. terminal 下指令" pod init"

      STEP4. project 資料夾內會多出Podfile ,編輯Podfile

      STEP5. Podfile裡面填入

      ProjectName 就是你Xcode project的名稱


      STEP6. terminal 下指令" pod install"

      STEP7. 最後在project 內記得要 import Alamofire


      如果出現

      App Transport Security has blocked a cleartext HTTP (http://) resource load since it is insecure. Temporary exceptions can be configured via your app's Info.plist file.


      在info.plist 按右鍵 -> open as source code 加入下面
      NSAppTransportSecurity
         
              NSAllowsArbitraryLoads
             
          

      [iOS] checkbok 使用 google material icon 製作

      恩....iOS竟然沒check box 的元件可以用

      只能用google material icon 代替了

      STEP.01

      https://design.google.com/icons/#ic_radio_button_checked

      去google material icon下載 png 檔案


      [iOS] checkbok 使用 google material icon 製作

      恩....iOS竟然沒check box 的元件可以用

      只能用google material icon 代替了

      STEP.01

      https://design.google.com/icons/#ic_radio_button_checked

      去google material icon下載 png 檔案


      [iOS] checkbok 使用 google material icon 製作

      恩....iOS竟然沒check box 的元件可以用

      只能用google material icon 代替了

      STEP.01

      https://design.google.com/icons/#ic_radio_button_checked

      去google material icon下載 png 檔案

      [iOS] Internal Rate of Return(IRR) calculator for swift version

      恩....需要計算IRR就參考這裡改成swift版本的

      有需要請自行取用

      GitHub : https://github.com/openopen114/IRR_calculator_swift_version"


      [iOS] Xcode thread 1 signal sigabrt 錯誤

      通常是連結錯誤

      但有時又不知道是哪裡或是哪個IBOutlet

      想這次是 table view 的 Identifier 忘記改(因為是直接複製過來的)


      可是錯誤只有說  thread 1 signal sigabrt  .....

      [解決] Xampp php 連接 MS SQL server sqlsrv問題

      剛在試 php 連MS SQL server 2014

      google 一下就有很多篇圖文並茂的教學

      有成功的話在 phpinfo.php 頁面上會出現 sqlsrv


      沒出現就是失敗了

      [iOS] ActivityIndicator 用法

      恩....通常在載入東西等待時可以用ActivityIndicator

      用法很簡單只要設定開始跟停止,還有停止後隱藏

      例如載入網頁時




      要停止後隱藏,要在這設定勾選

      [iOS] NSURL中文網址Crash解決辦法

      要是網址中有中文或其他符號有可能造成在開網頁時使得App crash 

      像是UIWebView開新網頁時 

      所以網址字串後面要用.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())!處理

      就像這樣

      [iOS] Alamofire 載入 json 檔前先清 cache

      在讀取外部json檔案時,iOS都會讀到cache裡面的
      所以就算json有更新,iOS還是抓到cache 舊的json檔

      所以要先清cache

      然後在載入json檔案
      蔡松霖
      Related Posts with Thumbnails