How to do it…

  1. Create a new project and skeleton application by executing the following command:
$ ng new angularjs-client
  1. Move to the angularjs-client directory and create server.go by executing the following command:
$ cd angularjs-client && touch server.go
  1. Copy the following code to server.go
package main
import
(
"encoding/json"
"log"
"net/http"
"github.com/gorilla/mux"
)
const
(
CONN_HOST = "localhost"
CONN_PORT = "8080"
)
type Route struct
{
Name string
Method string
Pattern string
HandlerFunc http.HandlerFunc
}
type Routes []Route
var routes = Routes
{
Route
{
"getEmployees",
"GET",
"/employees",
getEmployees,
},
Route
{
"addEmployee",
"POST",
"/employee/add",
addEmployee,
},
}
type Employee struct
{
Id string `json:"id"`
FirstName string `json:"firstName"`
LastName string `json:"lastName"`
}
type Employees []Employee
var employees []Employee
func init()
{
employees = Employees
{
Employee{Id: "1", FirstName: "Foo", LastName: "Bar"},
Employee{Id: "2", FirstName: "Baz", LastName: "Qux"},
}
}
func getEmployees(w http.ResponseWriter, r *http.Request)
{
json.NewEncoder(w).Encode(employees)
}
func addEmployee(w http.ResponseWriter, r *http.Request)
{
employee := Employee{}
err := json.NewDecoder(r.Body).Decode(&employee)
if err != nil
{
log.Print("error occurred while decoding employee
data :: ", err)
return
}
log.Printf("adding employee id :: %s with firstName
as :: %s and lastName as :: %s ", employee.Id,
employee.FirstName, employee.LastName)
employees = append(employees, Employee{Id: employee.Id,
FirstName: employee.FirstName, LastName: employee.LastName})
json.NewEncoder(w).Encode(employees)
}
func AddRoutes(router *mux.Router) *mux.Router
{
for _, route := range routes
{
router.
Methods(route.Method).
Path(route.Pattern).
Name(route.Name).
Handler(route.HandlerFunc)
}
return router
}
func main()
{
muxRouter := mux.NewRouter().StrictSlash(true)
router := AddRoutes(muxRouter)
router.PathPrefix("/").Handler(http.FileServer
(http.Dir("./dist/")))
err := http.ListenAndServe(CONN_HOST+":"+CONN_PORT, router)
if err != nil
{
log.Fatal("error starting http server :: ", err)
return
}
}
  1. Move to the angularjs-client directory and create models/employee.ts and service/employee.service.ts by executing the following command:
$ cd src/app/ && mkdir models && mkdir services && cd models && touch employee.ts && cd ../services && touch employee.service.ts
  1. Copy the following code to angularjs-client/src/app/models/employee.ts:
export class Employee 
{
constructor
(
public id: string,
public firstName: string,
public lastName: string
) {}
}
  1. Copy the following code to angularjs-client/src/app/services
    /employee.service.ts
    :
import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import { Employee } from "app/models/employee";

@Injectable()
export class EmployeeService 
{ constructor(private http: Http) { } getEmployees(): Observable<Employee[]>
{ return this.http.get("http://localhost:8080/employees") .map((res: Response) => res.json()) .catch((error: any) => Observable.throw(error.json().
error || 'Server error')); } addEmployee(employee: Employee): Observable<Employee>
{ let headers = new Headers({ 'Content-Type':
'application/json' }); let options = new RequestOptions({ headers: headers }); return this.http.post("http://localhost:8080/employee
/add", employee, options) .map(this.extractData) .catch(this.handleErrorObservable); } private extractData(res: Response)
{ let body = res.json(); return body || {}; } private handleErrorObservable(error: Response | any)
{ console.error(error.message || error); return Observable.throw(error.message || error); } }
  1. Replace the code of angularjs-client/src/app/app.component.html with the following:
<div class = "container" style="padding:5px">
<form>
<div class = "form-group">
<label for = "id">ID</label>
<input type = "text" class = "form-control" id = "id"
required [(ngModel)] = "employee.id" name = "id">
</div>
<div class = "form-group">
<label for = "firstName">FirstName</label>
<input type = "text" class = "form-control" id =
"firstName" [(ngModel)] = "employee.firstName" name =
"firstName">
</div>
<div class = "form-group">
<label for = "lastName">LastName</label>
<input type = "text" class = "form-control" id =
"lastName" [(ngModel)] = "employee.lastName" name =
"lastName">
</div>
<div>
<button (click)="addEmployee()">Add</button>
</div>
</form>
</div>
<table>
<thead>
<th>ID</th>
<th>FirstName</th>
<th>LastName</th>
</thead>
<tbody>
<tr *ngFor="let employee of employees">
<td>{{employee.id}}</td>
<td>{{employee.firstName}}</td>
<td>{{employee.lastName}}</td>
</tr>
</tbody>
</table>
  1. Replace the code oangularjs-client/src/app/app.component.ts with the following:
import { Component, OnInit } from '@angular/core';
import { EmployeeService } from "app/services/employee.service";
import { Employee } from './models/employee';

@Component
({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], }) export class AppComponent implements OnInit
{ title = 'app'; employee = new Employee('', '', ''); employees; constructor(private employeeService: EmployeeService) { } ngOnInit(): void
{ this.getEmployees(); } getEmployees(): void
{ this.employeeService.getEmployees() .subscribe(employees => this.employees = employees); } addEmployee(): void
{ this.employeeService.addEmployee(this.employee) .subscribe
(
employee =>
{ this.getEmployees(); this.reset(); } ); } private reset()
{ this.employee.id = null; this.employee.firstName = null; this.employee.lastName = null; } }
  1. Replace the code of angularjs-client/src/app/app.module.ts with the following:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpModule } from '@angular/http';
import { AppComponent } from './app.component';
import { EmployeeService } from "app/services/employee.service";
import { FormsModule } from '@angular/forms';

@NgModule
({
declarations:
[
AppComponent
],
imports:
[
BrowserModule, HttpModule, FormsModule
],
providers: [EmployeeService],
bootstrap: [AppComponent]
})
export class AppModule { }

With everything in place, the directory structure should look like the following:

  1. Move to the angularjs-client directory and execute the following commands to build the project artifacts and run the program:
$ ng build
$ go run server.go
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.194.57