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






      蔡松霖
      Related Posts with Thumbnails