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!');	
    }
  );
相关推荐
hunterandroid2 小时前
HarmonyOS WebSocket 实战:断线重连、心跳保活与连接状态机设计
前端
hunterandroid2 小时前
StateFlow 与 SharedFlow 的边界:状态与事件的正确建模
android·前端
心念科技2 小时前
1、搜索表单 xnSearch(基于:心念后台,后端 Java 21 + Spring Boot 4 + Spring Cloud,前端提供 ReactVue3+TS、Vue3+JS、Vue2+JS
前端
计算机魔术师2 小时前
Dwarkesh Patel 对 OpenAI/Hugging Face 事件的爆款解读被指危险误导
前端
自进化Agent智能体3 小时前
Hermes GitHub PR 审查 —— 自动化代码评审
前端
涛涛ing5 小时前
OpenAI Astra 泄露:零样本生成 3D 网页,前端开发者慌了吗?
前端
ssshooter5 小时前
现在网页都能提供 MCP 了?!
前端·人工智能·程序员
杉氧5 小时前
状态管理变迁史:为什么我们放弃了 Redux 选择 Zustand?
android·前端·react native
cidy_986 小时前
OpenCode 手动配置火山方舟 Agent Plan 教程
前端
鹏多多6 小时前
PC 网站接入微信登录,这 10 个坑我替你踩完了!
前端·javascript·vue.js