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!');	
    }
  );
相关推荐
@PHARAOH1 小时前
WHAT - GitLens vs Fork
前端
yqcoder2 小时前
前端性能优化:如何减少重绘与重排?
前端·性能优化
洋子2 小时前
Yank Note 系列 13 - 让 AI Agent 进入笔记工作流
前端·人工智能
wenzhangli75 小时前
Ooder A2UI 核心架构深度解析:WEB 拦截层的设计与实现
前端·架构
前端百草阁5 小时前
【前端性能优化全链路指南】从开发编写到构建运行的多维度实践
前端·性能优化
女生也可以敲代码5 小时前
AI时代下的50道前端开发面试题:从基础到大模型应用
前端·面试
ZhengEnCi5 小时前
M5-markconv自定义CSS样式指南 📝
前端·css·python
IT_陈寒6 小时前
SpringBoot自动配置的坑差点让我加班到天亮
前端·人工智能·后端
xingpanvip6 小时前
星盘接口开发文档:星相日历接口指南
android·开发语言·前端·css·php·lua
@PHARAOH6 小时前
WHAT - GitLens supercharged 插件
前端