• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

angular网络请求

武飞扬头像
勘察加熊人
帮助1

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_general_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

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgbecch
系列文章
更多 icon
同类精品
更多 icon
继续加载