Angular【http服务端交互】

启用 Http 服务

  • 打开AppModule
  • @angular/common/http导入 HttpClientModule
  • 添加到 @NgModule 的 imports 数组
typescript 复制代码
// app.module.ts:
 
import {NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
 
// 导入 HttpClientModule
import {HttpClientModule} from '@angular/common/http';
 
@NgModule({
  imports: [
    BrowserModule,
    // 'imports' 添加 HttpClientModule 模块
    HttpClientModule,
  ],
})
export class MyAppModule {}

发起一个 get 请求

typescript 复制代码
@Component(...)
export class MyComponent implements OnInit {
 
  results: string[];
 
  // 将HttpClient注入到组件或服务中
  constructor(private http: HttpClient) {}
 
  ngOnInit(): void {
    // 发起 HTTP 请求
    this.http.get('/api/items').subscribe(data => {
      // 从JSON响应中读取结果字段
      this.results = data['results'];
    });
  }
}

错误处理

typescript 复制代码
http
  .get('/api/items')
  .subscribe(
    // Successful responses call the first callback.
    data => {...},
    // Errors will call this callback instead:
    err => {
      console.log('Something went wrong!');	
    }
  );
相关推荐
DianSan_ERP7 小时前
电商架构演进:如何在高并发场景下实现多平台API的标准化履约?
运维·前端·网络·安全·架构·自动化
碎_浪10 小时前
给键盘党的英语记忆工具:我做了一款「打字背单词」桌面应用
前端·程序员·ai编程
阿成学长_Cain11 小时前
Linux dirs命令详解|Bash目录堆栈管理快速切换目录实战教程
linux·运维·前端·数据库
yqcoder11 小时前
httpOnly 是什么,又有什么用?
开发语言·前端·javascript
IT_陈寒11 小时前
Java的Stream.parallel()把我CPU跑爆了,这种优化要谨慎
前端·人工智能·后端
小皮虾12 小时前
小程序首页性能优化实战:从 4 秒到 1.8 秒
前端·微信小程序
山河木马12 小时前
GPU自动处理专题1-裁剪到底在裁什么(裁剪)
前端·webgl·计算机图形学
奔跑的蜗牛ing12 小时前
CentOS Nginx 安装与静态文件服务器配置指南
前端·面试·架构
子兮曰12 小时前
Bun 重写为 Rust:11天、64个Claude、16.5万美元,一次改变行业认知的激进实验
前端·后端·bun