IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> JavaScript知识库 -> angular网络请求 -> 正文阅读

[JavaScript知识库]angular网络请求

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);
    // Here we are passing the endpoints from gorest api to post data
    return this.http.post<any>('https://gorest.co.in/public/v2/users', data);
  }

  getUserData() {
    // Here we are passing the endpoints from gorest api to get all data
    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(): Observable<any> {
      let url = "http://127.0.0.1:8080/doLogin";
      this.http.post(url, {"id": 22, "email": "1452478563@qq.com", "last_name": "苹果"}).pipe(
        catchError((e) => {
          console.log(e.error.error)
          return throwError(e);
        })
        map()
      )
        .subscribe((response) => {
          console.log(response)
        })

    }*/


  // http://192.168.101.227:5000/test/add?id=103&email=5484075190@qq.com&last_name=刘备

  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{
  // Auth
  AuthRegister = "/Auth/Register",
  AuthLogin = "/Auth/Login",
  AuthSendOtp = "/Auth/SendOtp",
  AuthVerifyOtp = "/Auth/VerifyOtp",
  AuthResetPwd = "/Auth/ResetPwd",
  AuthForgetPwd = "/Auth/ForgetPwd",
  AuthUserInfo = "/Auth/UserInfo",
  AuthUpdateUser = "/Auth/UpdateUser",

  // File
  FileCarUpload = "/File/CarUpload",
  FileAvatarUpload = "/File/AvatarUpload",

  // Car
  CarCreate = "/Car/Create",
  CarList = "/Car/List",
}

export interface ApiModel<T>{
  errorMsg: string;
  data: T
}

// Auth/Register
export interface AuthRegisterReq{
  custId: string;
  password: string;
  name: string;
  cellphone: string;
  email: string;
  gender: "male" | "female";
  birthdate: Date;
  role: "user" | "partner";
}

// Auth/Login
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
}

// Auth/SendOtp
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;
}

// Auth/VerifyOtp
export interface AuthVerifyOtpReq{
  cellphone: string;
  verifyCode: string;
}

// Auth/ResetPwd
export interface AuthResetPwdReq{
  oldPassword: string;
  newPassword: string;
}

// Auth/ForgetPwd
export interface AuthForgetPwdReq{
  custId: string;
  email: string;
}

// Auth/UpdateUser
export interface AuthUpdateUserReq{
  name: string;
  gender: 'male' | 'female';
  cellphone: string;
  email: string;
  birthdate: Date;
}

// Car/Create
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;
}

// Car/List

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";
}

// File/CarUpload
export interface FileCarUploadReq{
  carId: string;
  docName: string;
  docType: "vl01" | "vl02" | "car01" | "car02" | "car03" | "car04" | "car05" | "car06" | "car07" | "car08" | "car09";
  docContent: string;
  mimeType: string;
}

// File/AvatarUpload
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;


    // http://192.168.101.227:8080/test/query?id=2
    @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  //    @GeneratedValue(strategy = GenerationType.IDENTITY) // 自增主键
    @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

  JavaScript知识库 最新文章
ES6的相关知识点
react 函数式组件 & react其他一些总结
Vue基础超详细
前端JS也可以连点成线(Vue中运用 AntVG6)
Vue事件处理的基本使用
Vue后台项目的记录 (一)
前后端分离vue跨域,devServer配置proxy代理
TypeScript
初识vuex
vue项目安装包指令收集
上一篇文章      下一篇文章      查看所有文章
加:2022-05-08 07:59:01  更:2022-05-08 08:00:13 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/23 22:44:33-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码