Spring Angular CRUD應(yīng)用程序

在本節(jié)中,我們將開發(fā)一個(gè)CRUD(創(chuàng)建-讀取-更新-刪除)Web應(yīng)用程序。該應(yīng)用程序包含學(xué)生表單,該表單包含CRUD功能,例如添加,查看,刪除和更新學(xué)生。在這種集成中,我們使用Spring Boot處理后端部分,使用Angular處理前端部分。

工作應(yīng)用程序

一旦我們將應(yīng)用程序部署到服務(wù)器上,就會(huì)在Web瀏覽器中生成學(xué)生表格。 該表單有助于添加和查看學(xué)生。 點(diǎn)擊添加學(xué)生鏈接后,頁(yè)面會(huì)重定向到創(chuàng)建學(xué)生表格,我們可以通過填寫所需的詳細(xì)信息并提交來(lái)添加學(xué)生。 使用查看學(xué)生鏈接,我們可以獲取現(xiàn)有學(xué)生的詳細(xì)信息。在這里,每個(gè)學(xué)生還包含更新和刪除鏈接。 因此,我們可以更新學(xué)生的詳細(xì)信息,也可以從數(shù)據(jù)庫(kù)中刪除他們。 完成后,在網(wǎng)絡(luò)瀏覽器中提供URL http://localhost: 4200/。

要使用的工具

使用任何IDE來(lái)開發(fā)Spring和Hibernate項(xiàng)目??赡苁荢TS/Eclipse/Netbeans。在這里,我們正在使用STS(Spring工具套件)。 用于數(shù)據(jù)庫(kù)的MySQL。 使用任何IDE來(lái)開發(fā)Angular項(xiàng)目。它可能是Visual Studio代碼/Sublime。在這里,我們正在使用Visual Studio Code。 服務(wù)器: Apache Tomcat/JBoss/Glassfish/Weblogic/Websphere。

我們使用的技術(shù)

在這里,我們正在使用以下技術(shù):

SpringBoot2 Hibernate5 Angular6 MYSQL

創(chuàng)建數(shù)據(jù)庫(kù)

讓我們創(chuàng)建數(shù)據(jù)庫(kù) indigo 。無(wú)需創(chuàng)建表,因?yàn)镠ibernate會(huì)自動(dòng)創(chuàng)建它。

Spring模塊

讓我們看看我們需要遵循的Spring Boot的目錄結(jié)構(gòu):

Angular + Spring CRUD示例

要開發(fā)CRUD應(yīng)用程序,請(qǐng)執(zhí)行以下步驟: -

將依賴項(xiàng)添加到pom.xml文件。

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.1.4.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.main</groupId>
	<artifactId>Student</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>Student</name>
	<description>Demo project for Spring Boot</description>
	<properties>
		<java.version>1.8</java.version>
	</properties>
	<dependencies>
	
		<dependency>
		    <groupId>org.springframework.boot</groupId>
		    <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
		</dependency>
	
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>
	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
</project>

創(chuàng)建配置類
我們執(zhí)行基于注釋的配置,而不是XML。因此,我們創(chuàng)建一個(gè)類Config.java并在其中指定所需的配置。但是,還有一個(gè)配置類StudentApplication.java。此類由Spring Boot自動(dòng)提供。q

Config.java

package config;
import java.util.Properties;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScans;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
@Configuration
@EnableTransactionManagement
@EnableAutoConfiguration(exclude = { HibernateJpaAutoConfiguration.class})
@ComponentScans(value = { @ComponentScan("boot.entry"),
	      @ComponentScan("Model"),
	      @ComponentScan("Controller"),
	      @ComponentScan("DAO"),
	      @ComponentScan("Miscallaneous"),
	      @ComponentScan("Service")})
public class Config {
	 @Value("${db.driver}")
	    private String DB_DRIVER;
	    @Value("${db.password}")
	    private String DB_PASSWORD;
	    @Value("${db.url}")
	    private String DB_URL;
	    @Value("${db.username}")
	    private String DB_USERNAME;
	    @Value("${hibernate.dialect}")
	    private String HIBERNATE_DIALECT;
	    @Value("${hibernate.show_sql}")
	    private String HIBERNATE_SHOW_SQL;
	    @Value("${hibernate.hbm2ddl.auto}")
	    private String HIBERNATE_HBM2DDL_AUTO;
	    @Value("${entitymanager.packagesToScan}")
	    private String ENTITYMANAGER_PACKAGES_TO_SCAN;
	    @Bean
	    public LocalSessionFactoryBean sessionFactory() {
	        LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
	        sessionFactory.setDataSource(dataSource());
	        sessionFactory.setPackagesToScan(ENTITYMANAGER_PACKAGES_TO_SCAN);
	        Properties hibernateProperties = new Properties();
	        hibernateProperties.put("hibernate.dialect", HIBERNATE_DIALECT);
	        hibernateProperties.put("hibernate.show_sql", HIBERNATE_SHOW_SQL);
	        hibernateProperties.put("hibernate.hbm2ddl.auto", HIBERNATE_HBM2DDL_AUTO);
	        sessionFactory.setHibernateProperties(hibernateProperties);
	        return sessionFactory;
	    }
	    @Bean
	    public DataSource dataSource() {
	        DriverManagerDataSource dataSource = new DriverManagerDataSource();
	        dataSource.setDriverClassName(DB_DRIVER);
	        dataSource.setUrl(DB_URL);
	        dataSource.setUsername(DB_USERNAME);
	        dataSource.setPassword(DB_PASSWORD);
	        return dataSource;
	    }
	    @Bean
	    public HibernateTransactionManager transactionManager() {
	        HibernateTransactionManager txManager = new HibernateTransactionManager();
	        txManager.setSessionFactory(sessionFactory().getObject());
	        return txManager;
	    }
	    
	    @Bean
	    public InternalResourceViewResolver jspViewResolver() {
	        InternalResourceViewResolver resolver= new InternalResourceViewResolver();
	        resolver.setPrefix("/views/");
	        resolver.setSuffix(".jsp");
	        return resolver;
	    } 
	   
	   
	   
	}

StudentApplication.java

package config;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class StudentApplication {
	public static void main(String[] args) {
		SpringApplication.run(StudentApplication.class, args);
	}
}

創(chuàng)建實(shí)體類
在這里,我們將創(chuàng)建一個(gè)Entity/POJO(普通的舊Java對(duì)象)類。

Student.java

package Model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="student")
public class Student {
	@Id
	@GeneratedValue(strategy=GenerationType.IDENTITY)
	private int student_id;
	private String student_name;
	private String student_email;
	private String student_branch;
	public int getStudent_id() {
		return student_id;
	}
	public void setStudent_id(int student_id) {
		this.student_id = student_id;
	}
	public String getStudent_name() {
		return student_name;
	}
	public void setStudent_name(String student_name) {
		this.student_name = student_name;
	}
	public String getStudent_email() {
		return student_email;
	}
	public void setStudent_email(String student_email) {
		this.student_email = student_email;
	}
	public String getStudent_branch() {
		return student_branch;
	}
	public void setStudent_branch(String student_branch) {
		this.student_branch = student_branch;
	}
	
}

創(chuàng)建DAO界面
在這里,我們正在創(chuàng)建DAO界面以執(zhí)行與數(shù)據(jù)庫(kù)相關(guān)的操作。

Student_DAO.java

package DAO;
import java.util.List;
import Model.Student;
public interface Student_DAO {
	public boolean saveStudent(Student student);
	public List<Student> getStudents();
	public boolean deleteStudent(Student student);
	public List<Student> getStudentByID(Student student);
	public boolean updateStudent(Student student);
}

創(chuàng)建DAO接口實(shí)現(xiàn)類

Student_DAO_Imp.java

package DAO;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import Model.Student;
@Repository
public class Student_DAO_Imp  implements Student_DAO{
	@Autowired
	private SessionFactory sessionFactory;
	
	@Override
	public boolean saveStudent(Student student) {
		boolean status=false;
		try {
			sessionFactory.getCurrentSession().save(student);
			status=true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return status;
	}
	@Override
	public List<Student> getStudents() {
		Session currentSession = sessionFactory.getCurrentSession();
		Query<Student> query=currentSession.createQuery("from Student", Student.class);
		List<Student> list=query.getResultList();
		return list;
	}
	@Override
	public boolean deleteStudent(Student student) {
		boolean status=false;
		try {
			sessionFactory.getCurrentSession().delete(student);
			status=true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return status;
	}
	@Override
	public List<Student> getStudentByID(Student student) {
		Session currentSession = sessionFactory.getCurrentSession();
		Query<Student> query=currentSession.createQuery("from Student where student_id=:student_id", Student.class);
		query.setParameter("student_id", student.getStudent_id());
		List<Student> list=query.getResultList();
		return list;
	}
	@Override
	public boolean updateStudent(Student student) {
		boolean status=false;
		try {
			sessionFactory.getCurrentSession().update(student);
			status=true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return status;
	}
	
	
}

創(chuàng)建服務(wù)層接口

在這里,我們正在創(chuàng)建一個(gè)服務(wù)層接口,充當(dāng)DAO和實(shí)體類之間的橋梁。

Student_Service.java

package Service;
import java.util.List;
import Model.Student;
public interface Student_Service {
	
	public boolean saveStudent(Student student);
	public List<Student> getStudents();
	public boolean deleteStudent(Student student);
	public List<Student> getStudentByID(Student student);
	public boolean updateStudent(Student student);
}

創(chuàng)建服務(wù)層實(shí)現(xiàn)類

Student_Service_Imp.java

package Service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import DAO.Student_DAO;
import Model.Student;
@Service
@Transactional
public class Student_Service_Imp implements Student_Service {
 
	@Autowired
	private Student_DAO studentdao;
	
	@Override
	public boolean saveStudent(Student student) {
		return studentdao.saveStudent(student);
	}
	@Override
	public List<Student> getStudents() {
		return studentdao.getStudents();
	}
	@Override
	public boolean deleteStudent(Student student) {
		return studentdao.deleteStudent(student);
	}
	@Override
	public List<Student> getStudentByID(Student student) {
		return studentdao.getStudentByID(student);
	}
	@Override
	public boolean updateStudent(Student student) {
		return studentdao.updateStudent(student);
	}
}

創(chuàng)建控制器類

Controller.java

package Controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import Model.Student;
import Service.Student_Service;
@RestController
@CrossOrigin(origins="http://localhost:4200")
@RequestMapping(value="/api")
public class Controller {
	
	@Autowired
	private Student_Service studentservice;
	
	@PostMapping("save-student")
	public boolean saveStudent(@RequestBody Student student) {
		 return studentservice.saveStudent(student);
		
	}
	
	@GetMapping("students-list")
	public List<Student> allstudents() {
		 return studentservice.getStudents();
		
	}
	
	@DeleteMapping("delete-student/{student_id}")
	public boolean deleteStudent(@PathVariable("student_id") int student_id,Student student) {
		student.setStudent_id(student_id);
		return studentservice.deleteStudent(student);
	}
	@GetMapping("student/{student_id}")
	public List<Student> allstudentByID(@PathVariable("student_id") int student_id,Student student) {
		 student.setStudent_id(student_id);
		 return studentservice.getStudentByID(student);
		
	}
	
	@PostMapping("update-student/{student_id}")
	public boolean updateStudent(@RequestBody Student student,@PathVariable("student_id") int student_id) {
		student.setStudent_id(student_id);
		return studentservice.updateStudent(student);
	}
}

編輯application.properties文件
在這里,我們正在編輯 src/main/resources 文件夾中的 application.properties 文件。以下文件包含配置屬性。

application.properties

# Database
db.driver= com.mysql.jdbc.Driver
db.url= jdbc:mysql://localhost:3306/indigo
db.username=root
db.password=

# Hibernate
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=update
entitymanager.packagesToScan=Model

Angular模塊

讓我們看看Angular的目錄結(jié)構(gòu):

Spring Angular CRUD應(yīng)用程序 創(chuàng)建一個(gè)Angular項(xiàng)目

使用以下命令創(chuàng)建一個(gè)Angular項(xiàng)目:

ng新的Angular

Spring Angular CRUD Application
Spring Angular CRUD Application

此處, Angular 是項(xiàng)目的名稱。

安裝Bootstrap CSS框架

使用以下命令

npm install bootstrap@3.3.7 --save

現(xiàn)在,在style.css中包含以下代碼文件。

@import "~bootstrap/dist/css/bootstrap.css";

安裝Angular-DataTable

使用以下命令在項(xiàng)目中安裝Angular數(shù)據(jù)表。

npm install Angular-datatable --save

Spring Angular CRUD應(yīng)用程序

必須包含 app.module.ts 文件的導(dǎo)入數(shù)組中的DataTableModule 。

生成組件
在Visual Studio中打開項(xiàng)目,然后使用以下命令生成Angular組件:
ng gc AddStudent
ng gc StudentList
Spring Angular CRUD應(yīng)用程序

我們還使用以下命令創(chuàng)建服務(wù)類: -

ng gs學(xué)生

Spring Angular CRUD應(yīng)用程序 編輯 app.module.ts 文件 導(dǎo)入路由-在這里,我們正在導(dǎo)入路由文件(app-routing.module.ts),并將其包含在imports數(shù)組中。 導(dǎo)入ReactiveFormsModule -在這里,我們將導(dǎo)入 ReactiveFormsModule 用于反應(yīng)形式,并在imports數(shù)組中指定它。 導(dǎo)入HttpModule -在這里,我們?yōu)榉?wù)器請(qǐng)求導(dǎo)入 HttpModule ,并在import數(shù)組中指定它。 注冊(cè)服務(wù)類-在這里,我們提到了提供者數(shù)組中的服務(wù)類。

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
import {DataTablesModule} from 'angular-datatables';
import { StudentListComponent } from './student-list/student-list.component';
import { AddStudentComponent } from './add-student/add-student.component';
@NgModule({
  declarations: [
    AppComponent,
    StudentListComponent,
    AddStudentComponent,
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule,
    ReactiveFormsModule,
    HttpClientModule,
    DataTablesModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

編輯 app-routing.module.ts 文件

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { StudentListComponent } from './student-list/student-list.component';
import { AddStudentComponent } from './add-student/add-student.component';
const routes: Routes = [
  { path: '', redirectTo: 'view-student', pathMatch: 'full' },
  { path: 'view-student', component: StudentListComponent },
  { path: 'add-student', component: AddStudentComponent },
];
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

編輯 app.component.html 文件

    <div  class="container-fluid">
    <nav class="navbar navbar-expand-sm bg-dark navbar-dark">
        <ul class="navbar-nav">
          <li class="nav-item ">
            <a routerLink="view-student" class="nav-link" class="btn btn-primary active" role="button" >View Student</a>
          </li> 
          <li class="nav-item">
            <a  routerLink="add-student" class="nav-link" class="btn btn-primary active" role="button" >Add Student</a>
          </li>          
        </ul>
      </nav>   
        <router-outlet></router-outlet>
    </div>

創(chuàng)建 Student.ts

讓我們使用以下命令創(chuàng)建課程: -

ng g class Student

Spring Angular CRUD Application

現(xiàn)在,在 Student 類中指定必填字段。

export class Student {
    student_id:number;
    student_name:String;
    student_email:String;
    student_branch:String;
}

此類的目的是將指定的字段與Spring實(shí)體類的字段進(jìn)行映射。

編輯 student.service.ts 文件

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
  providedIn: 'root'
})
export class StudentService {
  private baseUrl = 'http://localhost:8080/api/';
  constructor(private http:HttpClient) { }
  getStudentList(): Observable<any> {
    return this.http.get(`${this.baseUrl}`+'students-list');
  }
  createStudent(student: object): Observable<object> {
    return this.http.post(`${this.baseUrl}`+'save-student', student);
  }
  deleteStudent(id: number): Observable<any> {
    return this.http.delete(`${this.baseUrl}/delete-student/${id}`, { responseType: 'text' });
  }
  getStudent(id: number): Observable<Object> {
    return this.http.get(`${this.baseUrl}/student/${id}`);
  }
  updateStudent(id: number, value: any): Observable<Object> {
    return this.http.post(`${this.baseUrl}/update-student/${id}`, value);
  }
  
}

編輯 add-student.component.ts 文件

import { Component, OnInit } from '@angular/core';
import { StudentService } from '../student.service';
import {FormControl,FormGroup,Validators} from '@angular/forms';
import { Student } from '../student';
@Component({
  selector: 'app-add-student',
  templateUrl: './add-student.component.html',
  styleUrls: ['./add-student.component.css']
})
export class AddStudentComponent implements OnInit {
  constructor(private studentservice:StudentService) { }
  student : Student=new Student();
  submitted = false;
  ngOnInit() {
    this.submitted=false;
  }
  studentsaveform=new FormGroup({
    student_name:new FormControl('' , [Validators.required , Validators.minLength(5) ] ),
    student_email:new FormControl('',[Validators.required,Validators.email]),
    student_branch:new FormControl()
  });
  saveStudent(saveStudent){
    this.student=new Student();   
    this.student.student_name=this.StudentName.value;
    this.student.student_email=this.StudentEmail.value;
    this.student.student_branch=this.StudentBranch.value;
    this.submitted = true;
    this.save();
  }
  
  save() {
    this.studentservice.createStudent(this.student)
      .subscribe(data => console.log(data), error => console.log(error));
    this.student = new Student();
  }
  get StudentName(){
    return this.studentsaveform.get('student_name');
  }
  get StudentEmail(){
    return this.studentsaveform.get('student_email');
  }
  get StudentBranch(){
    return this.studentsaveform.get('student_branch');
  }
  addStudentForm(){
    this.submitted=false;
    this.studentsaveform.reset();
  }
}

編輯 add-student.component.html 文件

<h3>Create Student</h3>
<div class="row">
  <div class="col-sm-4"></div>
  <div class="col-sm-4" >
    <div [hidden]="submitted" style="width: 400px;">
      <form [formGroup]="studentsaveform" #savestudent (ngSubmit)="saveStudent(saveStudent)">  <div class="form-group">
              <label for="name">Student Name</label>
              <input type="text" class="form-control"  formControlName="student_name" data-toggle="tooltip" 
                 data-placement="right" title="Enter Student Name" >
              <div class="alert alert-danger" *ngif = "(StudentName.touched) && (StudentName.invalid)" 
                style="margin-top: 5px;">
                  <span *ngIf="StudentName.errors.required">Student Name is Required</span>
                    <span *ngif = "StudentName.errors.minlength"> 
                        MinLength Error 
                    </span>                   
                </div>
          </div>
  
          <div class="form-group">
              <label for="name">Student Email</label>
              <input type="text" class="form-control" formControlName="student_email" 
                data-toggle="tooltip" data-placement="right" title="Enter Student Email">
                <div class="alert alert-danger" *ngif = "(StudentEmail.touched) && (StudentEmail.invalid)" 
                style="margin-top: 5px;">
                  <span *ngIf="StudentEmail.errors.required">Student Email is Required</span>
                    <span *ngif = "StudentEmail.errors.email"> 
                        Invalid Email Format 
                    </span>                   
                </div>
          </div>
  
          <div class="form-group">
              <label for="branch">Student Branch</label>
                <select class="form-control" formControlName="student_branch" data-toggle="tooltip" 
                      data-placement="right" title="Select Student Branch">
                    <option value="null">--Select Branch--</option>
                  <option value="B-Tech">B-Tech</option>
                  <option value="BCA">BCA</option>
                  <option value="MCA">MCA</option>
                  <option value="M-Tech">M-Tech</option>
                </select>
          </div>
  
          <button type="submit" class="btn btn-success">Submit</button>
      </form>
  </div>
  </div>
  <div class="col-sm-4"></div>
</div>
<div class="row">
  <div class="col-sm-4"></div>
  <div class="col-sm-4">
      <div [hidden]="!submitted">
         <h4>Student Added SuccessFully!</h4>
         <button (click)="addStudentForm()" class='btn btn-primary'>Add More Student</button>
      </div>      
  </div>
  <div class="col-sm-4"></div>
</div>

單擊 添加學(xué)生時(shí),將生成以下頁(yè)面:

Spring Angular CRUD應(yīng)用程序

現(xiàn)在,填寫所需的詳細(xì)信息,然后提交以添加學(xué)生。

編輯 student-list.component.ts 文件

import { Component, OnInit } from '@angular/core';
import { StudentService } from '../student.service';
import { Student } from '../student';
import { Observable,Subject } from "rxjs";
import {FormControl,FormGroup,Validators} from '@angular/forms';
@Component({
  selector: 'app-student-list',
  templateUrl: './student-list.component.html',
  styleUrls: ['./student-list.component.css']
})
export class StudentListComponent implements OnInit {
 constructor(private studentservice:StudentService) { }
  studentsArray: any[] = [];
  dtOptions: DataTables.Settings = {};
  dtTrigger: Subject<any>= new Subject();
  students: Observable<Student[]>;
  student : Student=new Student();
  deleteMessage=false;
  studentlist:any;
  isupdated = false;    
 
  ngOnInit() {
    this.isupdated=false;
    this.dtOptions = {
      pageLength: 6,
      stateSave:true,
      lengthMenu:[[6, 16, 20, -1], [6, 16, 20, "All"]],
      processing: true};   
    this.studentservice.getStudentList().subscribe(data =>{
    this.students =data;
    this.dtTrigger.next();
    })
  }
  
  deleteStudent(id: number) {
    this.studentservice.deleteStudent(id)
      .subscribe(
        data => {
          console.log(data);
          this.deleteMessage=true;
          this.studentservice.getStudentList().subscribe(data =>{
            this.students =data
            })
        },
        error => console.log(error));
  }
  updateStudent(id: number){
    this.studentservice.getStudent(id)
      .subscribe(
        data => {
          this.studentlist=data           
        },
        error => console.log(error));
  }
  studentupdateform=new FormGroup({
    student_id:new FormControl(),
    student_name:new FormControl(),
    student_email:new FormControl(),
    student_branch:new FormControl()
  });
  updateStu(updstu){
    this.student=new Student(); 
   this.student.student_id=this.StudentId.value;
   this.student.student_name=this.StudentName.value;
   this.student.student_email=this.StudentEmail.value;
   this.student.student_branch=this.StudentBranch.value;
   console.log(this.StudentBranch.value);
   
   this.studentservice.updateStudent(this.student.student_id,this.student).subscribe(
    data => {     
      this.isupdated=true;
      this.studentservice.getStudentList().subscribe(data =>{
        this.students =data
        })
    },
    error => console.log(error));
  }
  get StudentName(){
    return this.studentupdateform.get('student_name');
  }
  get StudentEmail(){
    return this.studentupdateform.get('student_email');
  }
  get StudentBranch(){
    return this.studentupdateform.get('student_branch');
  }
  get StudentId(){
    return this.studentupdateform.get('student_id');
  }
  changeisUpdate(){
    this.isupdated=false;
  }
}

編輯 student-list.component.html 文件

<div class="panel panel-default">
  <div class="panel-heading">
      <h1 style="text-align: center">Students</h1><br>
      <div class="row" [hidden]="!deleteMessage">
           
                <div class="col-sm-4"></div>
                <div class="col-sm-4">
                        <div class="alert alert-info alert-dismissible">
                                <button type="button" class="close" data-dismiss="alert">×</button>
                                <strong>Student Data Deleted</strong>
                        </div>
                </div>
                <div class="col-sm-4"></div>
        </div>           
    </div>
  
  <div class="panel-body">
      <table  class="table table-hover table-sm" datatable [dtOptions]="dtOptions"
      [dtTrigger]="dtTrigger"  >
          <thead class="thead-light">
              <tr>
                  <th>Student Name</th>
                  <th>Student Email</th>
                  <th>Student Branch</th>
                  <th>Action</th>
                  
              </tr>
          </thead>
          <tbody>
               <tr *ngFor="let student of students ">
                  <td>{{student.student_name}}</td>
                  <td>{{student.student_email}}</td>
                  <td>{{student.student_branch}}</td>
                  <td><button (click)="deleteStudent(student.student_id)" class='btn btn-primary'><i class="fa fa-futboll-0">Delete</i></button> 
                    <button (click)="updateStudent(student.student_id)" class='btn btn-info'
                    data-toggle="modal" data-target="#myModal">Update</button>  </td>
                </tr> 
          </tbody><br>
      </table>
  </div>
</div> 
<div class="modal" id="myModal">
        <div class="modal-dialog">
          <div class="modal-content">
                <form [formGroup]="studentupdateform" #updstu (ngSubmit)="updateStu(updstu)"><!-- Modal Header -->
            <div class="modal-header">
              <h4 class="modal-title" style="text-align: center">Update Student</h4>
              
            </div>
            
            <!-- Modal body -->
            <div class="modal-body" *ngFor="let student of studentlist " >
                <div [hidden]="isupdated">
                    <input type="hidden" class="form-control"  formControlName="student_id" [(ngModel)]="student.student_id">
                            <div class="form-group">
                                <label for="name">Student Name</label>
                                <input type="text" class="form-control"  formControlName="student_name" [(ngModel)]="student.student_name"  >
                            </div>
                    
                            <div class="form-group">
                                <label for="name">Student Email</label>
                                <input type="text" class="form-control" formControlName="student_email" [(ngModel)]="student.student_email">
                            </div>
                    
                            <div class="form-group">
                                <label for="name">Student Branch</label>
                                  <select class="form-control" formControlName="student_branch" required>                                   
                                    <option value="B-Tech" [selected]="'B-Tech' == student.student_branch">B-Tech</option>
                                    <option value="BCA" [selected]="'BCA' == student.student_branch">BCA</option>
                                    <option value="MCA" [selected]="'MCA' == student.student_branch" >MCA</option>
                                    <option value="M-Tech" [selected]="'M-Tech' == student.student_branch">M-Tech</option>
                                  </select>                               
                            </div>                   
                  </div>  
                  <div [hidden]="!isupdated">
                      <h4>Student Detail Updated!</h4>
                  </div>        
                    
            </div>
            
            <!-- Modal footer -->
            <div class="modal-footer" >
              <button type="submit" class="btn btn-success" [hidden]="isupdated">Update</button>
              <button type="button" class="btn btn-danger" data-dismiss="modal" (click)="changeisUpdate()">Close</button>
            </div>
            
        </form>
          </div>
        </div>
      </div>

單擊 查看學(xué)生時(shí),將生成以下頁(yè)面:

Spring Angular CRUD應(yīng)用程序

單擊 更新學(xué)生時(shí),將出現(xiàn)以下引導(dǎo)程序模式:

Spring Angular CRUD Application

在這里,我們可以更新現(xiàn)有學(xué)生的詳細(xì)信息。

單擊 Delete (刪除),現(xiàn)有學(xué)生將被刪除從數(shù)據(jù)庫(kù)中。讓我們?cè)趧h除特定學(xué)生后查看結(jié)果。

Spring Angular CRUD應(yīng)用程序


丰满人妻一级特黄a大片,午夜无码免费福利一级,欧美亚洲精品在线,国产婷婷成人久久Av免费高清