step1: 网络请求,集成api D:\vue\nghttpdemo\src\app\services\cliente.service.ts
import {HttpClient, HttpHeaders, HttpClientModule} from '@angular/common/http';
import {Injectable} from '@angular/core';
import {Observable, catchError, throwError, map, tap} from 'rxjs';
import {UserBean} from "../interfaces/api.model";
@Injectable({
providedIn: 'root',
})
export class ApiService {
private httpHeaders = new HttpHeaders({ 'Content-Type': 'application/json' });
constructor(private http: HttpClient) {
}
postUserData(data: any) {
console.log('Data', data);
return this.http.post<any>('https://gorest.co.in/public/v2/users', data);
}
getUserData() {
return this.http.get<any>('https://gorest.co.in/public/v2/users');
}
getUserId(id: number): Observable<any> {
return this.http.get("http://192.168.101.227:5000/test/query?id=" + id).pipe(
catchError((e) => {
console.log(e.error.error)
return throwError(e);
})
);
}
getAllList(): Observable<any> {
return this.http.get("http://192.168.101.227:5000/test/query/all").pipe(
catchError((e) => {
console.log(e.error.error)
return throwError(e);
})
);
}
deleteAllList(id: number): Observable<UserBean> {
return this.http
.delete<UserBean>("http://192.168.101.227:5000/test/delete?id="+id)
.pipe(
catchError((e) => {
return throwError(e);
})
);
}
addAllList(id: number, email: string, lastName: string): Observable<UserBean> {
let formData = new FormData();
formData.append('id', id.toString());
formData.append('email', email);
formData.append('last_name', lastName);
return this.http.post("http://192.168.101.227:5000/test/add", formData).pipe(
map((response: any) => response as UserBean),
catchError((e) => {
console.log(e.error);
return throwError(e);
})
);
}
}
step2: 类型 引用类 D:\vue\nghttpdemo\src\app\interfaces\api.model.ts
export enum ApiEndpoint{
AuthRegister = "/Auth/Register",
AuthLogin = "/Auth/Login",
AuthSendOtp = "/Auth/SendOtp",
AuthVerifyOtp = "/Auth/VerifyOtp",
AuthResetPwd = "/Auth/ResetPwd",
AuthForgetPwd = "/Auth/ForgetPwd",
AuthUserInfo = "/Auth/UserInfo",
AuthUpdateUser = "/Auth/UpdateUser",
FileCarUpload = "/File/CarUpload",
FileAvatarUpload = "/File/AvatarUpload",
CarCreate = "/Car/Create",
CarList = "/Car/List",
}
export interface ApiModel<T>{
errorMsg: string;
data: T
}
export interface AuthRegisterReq{
custId: string;
password: string;
name: string;
cellphone: string;
email: string;
gender: "male" | "female";
birthdate: Date;
role: "user" | "partner";
}
export interface AuthLoginReq{
custId: string;
password: string;
role: "user" | "partner";
}
export interface AuthLoginResp {
accessToken: string;
name: string;
email: string;
cellphone: string;
gender: 'male' | 'female';
role: {
user: boolean;
partner: boolean;
};
birthdate: Date;
custId: string;
createdAt: Date;
avatar: Pic
}
export interface AuthSendOtpReq{
custId: string;
cellphone: string;
role: "user" | "partner";
}
export interface AuthSendOtpResp{
sendTime: Date;
custId: string | null;
name: string | null;
email: string | null;
gender: "male" | "female" | null;
birthdate: Date | null;
}
export interface AuthVerifyOtpReq{
cellphone: string;
verifyCode: string;
}
export interface AuthResetPwdReq{
oldPassword: string;
newPassword: string;
}
export interface AuthForgetPwdReq{
custId: string;
email: string;
}
export interface AuthUpdateUserReq{
name: string;
gender: 'male' | 'female';
cellphone: string;
email: string;
birthdate: Date;
}
export interface CarCreateReq{
model: "Model 3" | "Model X" | "Model S";
chargeType: "CCS2" | "TPC";
spec: "CCS2" | "TPC";
year: number;
season: number;
carNumber: string;
insuranceStartDate: Date;
insuranceEndDate: Date;
replaceValue: number;
insuranceCompany: string;
insuranceType: string;
sumAssured: number;
}
export interface CarCreateResp{
carId: string;
}
export interface Pic{
docPath: string;
base64: string | null;
}
export interface CarListResp{
model: "Model 3" | "Model X" | "Model S";
chargeType: "CCS2" | "TPC";
spec: "SR" | "LR" | "P";
year: number;
season: 1 | 2 | 3 | 4;
carNumber: string;
insuranceStartDate: Date;
insuranceEndDate: Date;
replaceValue: number;
insuranceCompany: string;
insuranceType: string;
sumAssured: number;
vl01?: Pic;
vl02?: Pic;
car01?: Pic;
car02?: Pic;
car03?: Pic;
car04?: Pic;
car05?: Pic;
car06?: Pic;
car07?: Pic;
car08?: Pic;
car09?: Pic;
status: "pending" | "approved" | "failed";
}
export interface FileCarUploadReq{
carId: string;
docName: string;
docType: "vl01" | "vl02" | "car01" | "car02" | "car03" | "car04" | "car05" | "car06" | "car07" | "car08" | "car09";
docContent: string;
mimeType: string;
}
export interface FileAvatarUploadReq{
docName: string;
docContent: string;
mimeType: string;
}
export interface UserBean{
id: number;
email: string;
last_name: string;
}
step3: 权限注册 D:\vue\nghttpdemo\src\app\app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
HttpClientModule,
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
step4: 功能代码 D:\vue\nghttpdemo\src\app\app.component.ts
import {Component, OnInit} from '@angular/core';
import {UserBean} from "../app/interfaces/api.model";
import {ApiService} from '../app/services/cliente.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'nghttpdemo';
constructor(private api: ApiService) {
}
ngOnInit(): void {
this.getAllData()
}
getAllData() {
this.api.getUserData().subscribe({
next: (res) => {
console.log(res)
},
error: (err) => {
console.log(err)
}
})
}
getTopBtn() {
this.api.getUserId(102).subscribe({
next: (res) => {
console.log(res.id)
console.log(res.email)
console.log(res.lastName)
},
error: (e) => {
console.log(e.error)
},
});
}
getAllListData() {
this.api.getAllList().subscribe({
next: (res) => {
console.log(res)
for (let i in res) {
console.log(res[i].lastName)
}
},
error: (e) => {
console.log(e.error)
},
});
}
addListData() {
this.api.addAllList(106,"899215963@qq.com","北川").subscribe({
next: (res) => {
console.log(res)
},
error: (e) => {
console.log(e.error)
},
})
}
deleteListData(){
this.api.deleteAllList(106).subscribe({
next: (res) => {
console.log('wrs delete')
console.log(res)
},
error: (e) => {
console.log(e.error)
},
})
}
}
step5: 布局 D:\vue\nghttpdemo\src\app\app.component.html
<div>
<button (click)="getTopBtn()">
获取单个
</button>
<button (click)="getAllListData()" style="margin-left: 30px">
获取所有
</button>
<button (click)="addListData()" style="margin-left: 30px">
添加
</button>
<button (click)="deleteListData()" style="margin-left: 30px">
删除
</button>
</div>
step6: mysql 数据库结构
CREATE TABLE `tbl_user` (
`id` int NOT NULL,
`email` varchar(255) DEFAULT NULL,
`last_name` varchar(50) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
step7: 跨域 后端处理器 D:\project\push\sprintboot_push\StudentServe\src\main\java\
package com.example.studentserve.controller;
import com.example.studentserve.entity.User;
import com.example.studentserve.service.UserRepostitory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Optional;
@CrossOrigin(origins = {"http://localhost:4200"})
@RestController
public class TestController {
@Autowired
UserRepostitory userRepostitory;
@RequestMapping(value = {"/test/add"}, method = RequestMethod.POST)
public User getAdd(HttpServletRequest request, HttpServletResponse response)
throws IOException {
String id = request.getParameter("id");
String email = request.getParameter("email");
String last_name = request.getParameter("last_name");
System.out.println(id + "\t" + email + "\t" + last_name);
User user = new User();
user.setId(Integer.parseInt(id));
user.setEmail(email);
user.setLastName(last_name);
userRepostitory.save(user);
return user;
}
@RequestMapping(value = {"/test/query"}, method = RequestMethod.GET)
public Optional<User> getQuery(HttpServletRequest request, HttpServletResponse response)
throws IOException {
String id = request.getParameter("id");
System.out.println(id + "\t");
Optional<User> user = userRepostitory.findById(Integer.parseInt(id));
return user;
}
@RequestMapping(value = {"/test/query/all"}, method = RequestMethod.GET)
public List<User> getQueryAll()
throws IOException {
List<User> user = userRepostitory.findAll();
return user;
}
@RequestMapping(value = {"/test/delete"}, method = RequestMethod.DELETE)
public List<User> getDelete(HttpServletRequest request, HttpServletResponse response)
throws IOException {
String id = request.getParameter("id");
System.out.println(id + "\t");
userRepostitory.deleteById(Integer.parseInt(id));
List<User> user = userRepostitory.findAll();
return user;
}
}
step8: 实体类 映射数据库
package com.example.studentserve.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "tbl_user")
public class User {
@Id
@Column(name = "id", unique = true, nullable = false)
private Integer id;
@Column(name = "last_name", length = 50)
private String lastName;
@Column
private String email;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
step9: jpa
package com.example.studentserve.service;
import com.example.studentserve.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepostitory extends JpaRepository<User, Integer> {
}
end
|