美文网首页Angular + ionic 5.x + Cordova混合开发Angular框架专题
Angular中使用json-serve模拟服务端接口以及请求后

Angular中使用json-serve模拟服务端接口以及请求后

作者: 听书先生 | 来源:发表于2021-11-09 22:34 被阅读0次

Angular 5.x之后get、post和服务器交互使用的是Angular中自有的封装的HttpClientModule模块。该模块用于发送 Http 请求,用于发送请求的方法都返回 Observable 对象。

1、使用json-serve模拟服务端接口

npm 安装json-serve,代替api的服务器接口为我们测试数据提供接口
npm install -g json-serve

然后我们在本地新建一份json文件用于存放一份数据


image.png
image.png

写好模拟数据后,在项目中启动接口服务:

输入指令:json-server --watch D:\data.json

image.png
2、Angular中去请求后台接口数据
  • 2.1、首先在app.module.ts中引入HttpClientModule并且注入:
import {HttpClientModule} from '@angular/common/http';
imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule,HttpClientModule],
image.png
  • 2.2、在页面的TS文件中引入HttpClient并在构造函数中声明一下:
import { HttpClient } from "@angular/common/http";

constructor(private http: HttpClient) {}
  • 2.3、get请求数据:
  constructor(private http: HttpClient) {
    const url = `http://localhost:3000/lists`;
    this.http.get(url).subscribe((res)=>{
      // 获取数据后的操作
      console.log(res);
    })
    for (var i = 0; i < 20; i++) { this.data.push(`这是第${i}条数据`); }
  }
image.png

可以看到,数据是请求成功了。

  • post请求数据:

post请求数据与get请求不太相同,post请求需要先在@angular/common/http依赖中导入HttpHeaders模块

  import { HttpClient, HttpHeaders } from "@angular/common/http";

  constructor(private http: HttpClient) {
    const httpOptions = { 
      headers: new HttpHeaders({ 'Content-Type': 'application/json' }) 
    };
    const url = `http://localhost:3000/lists`;
    const params = {
      currentPage:1,
      pageSize:10
    }
    this.http.post(url,params,httpOptions).subscribe((res)=>{
      // 获取数据后的操作
      console.log(res);
    })
  }
image.png

根据上图可以看出,post请求中需要传入2~3个参数,第一个是api接口的地址,第二个是body请求体,最后一个是请求需要设置的配置项。


image.png
  • jsonp请求数据:

在 app.module.ts 中引入 HttpClientModuleHttpClientJsonpModule 并注入

image.png
  constructor(private http: HttpClient) {
    const httpOptions = { 
      headers: new HttpHeaders({ 'Content-Type': 'application/json' }) 
    };
    const url = `http://****.com/api/lists`;
    this.http.jsonp(url,'callback').subscribe((res)=>{
      // 获取数据后的操作
      console.log(res);
    })
  }
3、使用第三方模块axios去请求数据

1、在使用axios之前首先需要安装axios

npm install axios --save

2、然后在使用到的地方去引入axios模块

import axios from 'axios';

3、使用axios请求数据

axios.get("/user?name='zhangsan'&id='123'").then(function (response) { 
  // handle success 
  console.log(response); 
}).catch(function (error) { 
  // handle error 
  console.log(error); 
}).then(function () { 
  // always executed 
});

相关文章

网友评论

    本文标题:Angular中使用json-serve模拟服务端接口以及请求后

    本文链接:https://www.haomeiwen.com/subject/pamvzltx.html