如何使用Angular 7制作凝乳

时间:2019-03-15 04:23:08

标签: angular angular7

请提供Angular 7的完整架构,包括服务,组件,模块和路由

1 个答案:

答案 0 :(得分:1)

对于该项目,我们使用了此版本

Angular CLI:7.2.3
节点:8.11.3
Npm:6.9.0
打字稿:3.2.2

list-emp.component.html

    <div class="container">
      <div class="col-md-12">
        <button class="btn btn-primary" routerLink="/add"> Add Employee</button>
      </div>
      <div class="col-md-12">
        <h2> User Details</h2>
        <div class="table-responsive table-container">
          <table class="table">
            <thead>
              <tr>
                <th>Name</th>
                <th>Email</th>
                <th>Salary</th>
                <th>Age</th>
                <th></th>
              </tr>
            </thead>
            <tbody>
              <tr *ngFor="let emp of employees">
                <td>{{emp.Name}}</td>
                <td>{{emp.Email}}</td>
                <td>{{emp.Salary}}</td>
                <td>{{emp.Age}}</td>
                <td>
                  <button routerLink="/edit/{{emp.Id}}" class="btn btn-info"> Edit</button>
                  <button (click)="deleteEmployee(emp.Id)" style="margin-left: 20px;" class="btn btn-info"> Delete</button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>

list-emp.component.ts

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

    @Component({
      selector: 'app-list-emp',
      templateUrl: './list-emp.component.html',
      styleUrls: ['./list-emp.component.css']
    })
    export class ListEmpComponent implements OnInit {

      employees: Employee[];

      constructor(private empService: EmployeeService, private router: Router, ) { }

      ngOnInit() {
        this.empService.getEmployees()
          .subscribe((data: Employee[]) => {
            this.employees = data;
          });
      }

      deleteEmployee(employeeId: number): void {
        if (confirm("are you sure you want to delete this record?")) {
          this.empService.deleteEmployees(employeeId)
            .subscribe(data => {
              this.employees = this.employees.filter(u => u.Id !== employeeId);
            })
        }
      }
    }

add-emp.component.html

    <div class="container">
      <div class="row">
        <div class="col-md-6 offset-md-3">
          <h3>{{empformlabel}}</h3>
          <form [formGroup]="addForm" (ngSubmit)="onSubmit()">
              <input type="hidden" formControlName="Id" class="form-control"/>
            <div class="form-group">
              <label>Name</label>
              <input type="text" formControlName="Name" class="form-control"
                [ngClass]="{ 'is-invalid': submitted && f.Name.errors }" />
              <div *ngIf="submitted && f.Name.errors" class="invalid-feedback">
                <div *ngIf="f.Name.errors.required">Name is required</div>
                <div *ngIf="f.Name.errors.minlength">Name must be at least 4 characters</div>
              </div>
            </div>
            <div class="form-group">
              <label>Email</label>
              <input type="text" formControlName="Email" class="form-control"
                [ngClass]="{ 'is-invalid': submitted && f.Email.errors }" />
              <div *ngIf="submitted && f.Email.errors" class="invalid-feedback">
                <div *ngIf="f.Email.errors.required">Email is required</div>
                <div *ngIf="f.Email.errors.email">Email must be a valid email address</div>
              </div>
            </div>
            <div class="form-group">
              <label>Salary</label>
              <input type="number" formControlName="Salary" class="form-control"
                [ngClass]="{ 'is-invalid': submitted && f.Salary.errors }" />
              <div *ngIf="submitted && f.Salary.errors" class="invalid-feedback">
                <div *ngIf="f.Salary.errors.required">Salary is required</div>
              </div>
            </div>
            <div class="form-group">
              <label>Age</label>
              <input type="number" formControlName="Age" class="form-control"
                [ngClass]="{ 'is-invalid': submitted && f.Age.errors }" />
              <div *ngIf="submitted && f.Age.errors" class="invalid-feedback">
                <div *ngIf="f.Age.errors.required">Age is required</div>
              </div>
            </div>
            <div class="form-group">
              <button class="btn btn-primary">{{empformbtn}}</button>
            </div>
          </form>
        </div>
      </div>
    </div>

add-emp.component.ts

    import { Component, OnInit } from '@angular/core';
    import { FormBuilder, FormGroup, Validators } from "@angular/forms";
    import { EmployeeService } from '../employee.service';
    import { Router, ActivatedRoute } from "@angular/router";

    @Component({
      selector: 'app-add-emp',
      templateUrl: './add-emp.component.html',
      styleUrls: ['./add-emp.component.css']
    })
    export class AddEmpComponent implements OnInit {
      empformlabel: string = 'Add Employee';
      empformbtn: string = 'Save';
      constructor(private formBuilder: FormBuilder, private router: Router, private route: ActivatedRoute, private empService: EmployeeService) {
      }

      addForm: FormGroup;
      btnvisibility: boolean = true;
      submitted: boolean = false;
      ngOnInit() {
        this.addForm = this.formBuilder.group({
          Id: [''],
          Name: ['', [Validators.required, Validators.minLength(4)]],
          Email: ['', [Validators.required, Validators.email]],
          Salary: ['', [Validators.required, Validators.minLength(4)]],
          Age: ['', [Validators.required]]
        });

        const id = +this.route.snapshot.paramMap.get('id');
        if (id) {
          this.empformlabel = 'Edit Employee';
          this.empformbtn = 'Update';
          this.getEmployeeDetails(id);
        }
      }

      getEmployeeDetails(id) {
        this.empService.getEmployeeById(id).subscribe(data => {
          this.addForm.patchValue(data);
        })
      }

      get f() { return this.addForm.controls; }

      onSubmit() {
        this.submitted = true;
        if (this.addForm.invalid) {
          return;
        }
        this.empService.saveUser(this.addForm.value)
          .subscribe(data => {
            this.router.navigate(['list']);
          },
            error => {
              alert(error);
            });
      }
    }

app-routing.module.ts

    import { NgModule } from '@angular/core';
    import { Routes, RouterModule } from '@angular/router';
    import { ListEmpComponent } from './list-emp/list-emp.component';  
    import { AddEmpComponent } from './add-emp/add-emp.component';  

    const routes: Routes = [
      { path: '', component: ListEmpComponent, pathMatch: 'full' },  
      { path: 'list', component: ListEmpComponent },  
      { path: 'add', component: AddEmpComponent },
      { path: 'edit/:id', component: AddEmpComponent }  
    ];

    @NgModule({
      imports: [RouterModule.forRoot(routes)],
      exports: [RouterModule]
    })
    export class AppRoutingModule { }

app.component.html

    <nav class="navbar navbar-default">
      <div class="container-fluid">
        <div class="navbar-header">
          <a class="navbar-brand" routerLink="/list">List of Emploee</a>
        </div>
      </div>
    </nav>
    <router-outlet></router-outlet>

app.module.ts

    import { BrowserModule } from '@angular/platform-browser';
    import { NgModule } from '@angular/core';
    import { HttpClientModule }    from '@angular/common/http';
    import { AppRoutingModule } from './app-routing.module';
    import { AppComponent } from './app.component';
    import { ListEmpComponent } from './list-emp/list-emp.component';
    import { AddEmpComponent } from './add-emp/add-emp.component';
    import { FormsModule, ReactiveFormsModule  } from '@angular/forms';

    @NgModule({
      declarations: [
        AppComponent,
        ListEmpComponent,
        AddEmpComponent
      ],
      imports: [
        BrowserModule,
        HttpClientModule,
        AppRoutingModule,
        FormsModule,
        ReactiveFormsModule 
      ],
      providers: [],
      bootstrap: [AppComponent]
    })
    export class AppModule { }

service / employee.service.ts

    import { Injectable } from '@angular/core';
    import { HttpClient } from '@angular/common/http';
    import { Employee } from './employee';
    @Injectable({
      providedIn: 'root'
    })
    export class EmployeeService {

      constructor(private http: HttpClient) { }
      baseUrl: string = 'http://localhost:61627/api/Employee/';

      getEmployees() {
        return this.http.get<Employee[]>(this.baseUrl + "Get");
      }

      deleteEmployees(id: number) {
        return this.http.delete<Employee[]>(this.baseUrl + 'Delete/' + id);
      }

      getEmployeeById(id: number) {
        return this.http.get<Employee>(this.baseUrl + 'GetById/' + id);
      }

      saveUser(employee: Employee) {
        return this.http.post(this.baseUrl + 'SaveUser', employee);
      }

    }

模型/Employee.ts

    export class Employee {  
        Id: number;  
        Name: string;  
        Salary: number;  
        Age: number;  
    }

style.css

    @import "~bootstrap/dist/css/bootstrap.css";  
    @import "~font-awesome/css/font-awesome.css";  


    .ng-valid[required], .ng-valid.required  {  
        border-left: 5px solid #42A948; /* green */  
      }  
      .ng-invalid:not(form)  {  
        border-left: 5px solid #a94442; /* red */  
      }  
      .mtop10{  
        margin-top:10px;  
      }  

      .invalid-feedback {
        color: #dc3545;
    }

用于引导程序和超棒的字体

npm install bootstrap @ 3-保存 npm install font-awesome@4.7.0-保存