angular使用http实现get和post请求

时间:2024-10-30 09:40:57

说明:
angular使用http实现get和post请求

提示:在运行本项目前,请先导入路由router,可以参考我上一篇文章。
效果图:
在这里插入图片描述

step1:E:\projectgood\ajsix\untitled4\package.json
“@angular/cdk”: “^18.2.10”,
“@angular/material”: “^18.2.10”,
step2:E:\projectgood\ajsix\untitled4\src\app\model\Service.ts


import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class Service {
  url = 'https://demo.restheart.org/messages';

  constructor(private http: HttpClient) {
  }

  public get(page: number = 1): Observable<Array<any>> {
    return this.http.get<Array<any>>(`${this.url}?pagesize=5&page=${page}`);
  }

  public size(): Observable<any> {
    return this.http.get(`${this.url}/_size`);
  }

  public delete(id: string): Observable<any> {
    return this.http.delete(`${this.url}/${id}`);
  }

  public getSingleCharacterz(id:string):Observable<any>{
    return this.http.get(`http://localhost:5000/api/water`)
  }

  public postSingleCharacterz(data: any): Observable<any> {
    const water =  {
      watername: '韩红牌纯净水',
      watericon: 'http://e.hiphotos.baidu.com/image/pic/item/a1ec08fa513d2697e542494057fbb2fb4316d81e.jpg',
      waterstyle: '最中幻想',
      watersize: '50L',
      waterprice: '32',
      shopaccount: '772024102801',
      shopname: '大润发超市'
    }
    return this.http.post(`http://localhost:5000/api/wateradd`, water);
  }


  public post(data: any): Observable<any> {
    const _data = {
      message: data.message,
      from: data.from
    };

    return this.http.post(this.url, _data);
  }
}

step3:E:\projectgood\ajsix\untitled4\src\app\user\user.component.html

<p>user works!</p>
<button mat-flat-button color="primary" (click)="onAcceptClick('element.operate')">查询</button>
<button mat-flat-button color="primary" (click)="onAddClick('element.operate')">新增</button>

step4:E:\projectgood\ajsix\untitled4\src\app\user\user.component.ts

import { Component, OnInit } from '@angular/core';
import { Observable, tap } from 'rxjs';
// import { Service } from './service';
import { FormsModule } from '@angular/forms';
import { AsyncPipe, JsonPipe, DatePipe } from '@angular/common';
import { HttpClient, HttpClientModule, HttpHandler } from '@angular/common/http';

import {Service} from '../model/Service';
import {MatButtonModule} from '@angular/material/button';

@Component({
  selector: 'app-user',
  standalone: true,
  imports: [FormsModule,AsyncPipe,JsonPipe,DatePipe,HttpClientModule,MatButtonModule],
  templateUrl: './user.component.html',
  providers:[Service],
  styleUrl: './user.component.css'
})
export class UserComponent implements OnInit  {

  constructor(private service: Service) {}


  ngOnInit(): void {
  }
  onAcceptClick(key: string): void {
    console.log('you click onAcceptClick'+key)


    this.service.getSingleCharacterz('1').subscribe(
      (result:any)=>{
        console.log(result)
      },(error:any)=>{
        console.error('Error : '+error);
      }
    );
  }


  onAddClick(key: string): void {
    console.log('you click onAddClick' + key)
    this.service
      .postSingleCharacterz('1')
      .pipe(tap())
      .subscribe((resp) =>{
        console.log(resp)
      });
  }

}

end