angular8 http请求

本文介绍了如何在Angular8中使用HttpClient进行HTTP请求。包括下载Postman辅助工具,安装和配置rest.client插件,以及在Angular应用中导入HttpClientModule。重点讲解了HttpClient的get、post、put、delete方法,并指出它们返回的是Observablle类型,需要订阅才能发送请求。同时,文章还提到了在不同环境中配置HTTP请求的方法和在组件中注入HttpClient的步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

https://www.getpostman.com  下载postman

在编辑器中搜索rest.client插件  

新建一个rest.http的文件

@baseUrl = https://jsonplaceholder.typicode.com

GET {{baseUrl}}/posts HTTP/1.1

###
POST  {{baseUrl}}/POST HTTP/1.1
Content-Type: : application/json

{
    "title":"这是一个测试的标题",
    "body":"这是一个测试的内容",
    "userId":1
}

Angular HttpClient

导入HttpClientModule 

只在根模块中导入

整个应用秩序导入一次,不要在其他的模块导入

在构造中注入  HtppClient

get/post/putdelete  方法对应于Http方法

这些方法是泛型的,可以直接把放回的JSON转换成对应类型

不规范的请求,使用request

返回的值是Observablle

必须订阅,才会发送请求,否则不会发送

 

编辑器中配置rest client

首先在设置中搜索 restclient  找到这个

添加  配置环境变量

"rest-client.environmentVariables":{
        "$shared": {
            "iCode":"123456"
        },
        "dev":{
            "host":"http://localhost:8080"
        },
        "prod":{
            "host":"http://local.dev"
        },
        "imooc":{
            "host":"http://apis.imooc.com/api"
        }
    }

 按F1 搜索rest client   选择 switch environmentVariable  再选择自己配置的环境变量

在 environment.prod.ts中也要添加配置

在app.module.ts中引入HttpClientModule         import { HttpClientModule } from '@angular/common/http'

在home.service.ts中

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { TopMenu, ImageSlider, Channel } from 'src/app/shared/components';
import { environment } from 'src/environments/environment';

@Injectable({
    providedIn:'root'
})
export class HomeService {
  constructor(private http:HttpClient){}
    getTabs(){
        return this.http.get<TopMenu[]>(`${environment.baseUrl}/tabs`,{params:{key:`${value}`}})
    }
    getChannels(){
        return this.http.get<Channel[]>(`${environment.baseUrl}/channels`,{params:{key:`${value}`}})
    }
    getImageSliders(){
        return this.http.get<ImageSlider[]>(`${environment.baseUrl}/banners`,{params:{key:`${value}`}})
    }
}

使用数据

this.service.getTabs().subscribe(tabs =>{
      this.menus = tabs;
    })

如果@component中添加changeDetection:ChangeDetectionStrategy.OnPush

this.service.getChannels().subscribe(channels => {
      this.channels = channels;
      this.cd.markForCheck();
})
this.service.getImageSliders().subscribe(imgs => {
      this.imageSliders = imgs;
      this.cd.markForCheck();
})

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值