Angular/cli中网络请求HTTPClient的使用

1.安装angular脚手架工具

具体参照官方文档

2.创建一个组件

ng g c components/httpstudy    
//表示在src/app目录下新建components文件夹在其下创个httpstudy组件

3.在app.component.html中写上这个组件使其显示出来

<app-httpstudy><app-httpstudy/>

4.在app.modules.ts里引入需要的模块

import { HttpClientModule } from '@angular/common/http';

imports: [BrowserModule, HttpClientModule],

5.在httpstudy.component.ts里引入

import { HttpClient, HttpErrorResponse } from '@angular/common/http';


export class HttpstudyComponent implements OnInit {
  result: any;
  constructor(private http: HttpClient) {}

  ngOnInit(): void {
    // 请求数据
    const url = 'http://localhost/user';
    this.http.get(url, { observe: 'response' }).subscribe(
      (data) => {
        this.result = data.body;
        console.log(data);
      },
      (err: HttpErrorResponse) => {
        if (err.error instanceof Error) {
          console.log('客户端出错', err.error.message);
        } else {
          console.log(`服务器返回${err.status},返回html:${err.error}`);
        }
      }
    );
  }
}

因为这里我们请求的地址是http://localhost/user 而这个地址我们并没有进行后台配置,所以暂时请求不到数据,后面会讲用node建个后台,使这个地址能访问。

6.在httpstudy.component.html页面拿数据

<ul *ngFor="let user of result; let i = index">
  <li>{{ i }}-{{ user.name }}---{{ user.age }}</li>
</ul>

7.搭建一个node后台提供数据

先在项目目录里安装express

npm i express --save

然后在项目根目录下新建serve.js

// 当做node后台的服务器
var express = require("express");
var app = express();
// 设置跨域访问
app.all("*", function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
  res.header("X-Powered-By", "3.2.1");
  res.header("Content-Type", "application/json;charset=utf-8");
  next();
});

var users = [
  { name: "小明", age: 13 },
  { name: "小红", age: 11 },
  { name: "小李", age: 21 },
  { name: "张飞", age: 31 },
  { name: "刘备", age: 34 },
];

app.get("/", function (req, res) {
  res.end("hello world");
});
app.get("/user", function (req, res) {
  res.json(users);
  res.end();
});
var server =    app.listen(80,function () {
    var host = server.address().address;
    var port = server.address().port
    console.log("应用实例,访问地址为http://%s:%s",host,port);
})

然后启动后台

node serve.js

运行如下图:
在这里插入图片描述
然后启动项目

ng serve --open

就可以访问到数据了
在这里插入图片描述

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值