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!');	
    }
  );
相关推荐
一心赚狗粮的宇叔1 小时前
03.Node.js依赖包补充说明及React&Node.Js项目
前端·react.js·node.js
子春一1 小时前
Flutter for OpenHarmony:音律尺 - 基于Flutter的Web友好型节拍器开发与节奏可视化实现
前端·flutter
JarvanMo1 小时前
150万开发者“被偷家”!这两款浓眉大眼的 VS Code 插件竟然是间谍
前端
亿元程序员1 小时前
大佬,现在AI游戏开发教程那么多,你不搞点卖给大学生吗?
前端
未来龙皇小蓝1 小时前
RBAC前端架构-02:集成Vue Router、Vuex和Axios实现基本认证实现
前端·vue.js·架构
晓得迷路了1 小时前
栗子前端技术周刊第 116 期 - 2025 JS 状态调查结果、Babel 7.29.0、Vue Router 5...
前端·javascript·vue.js
顾北122 小时前
AI对话应用接口开发全解析:同步接口+SSE流式+智能体+前端对接
前端·人工智能
摸鱼的春哥2 小时前
春哥的Agent通关秘籍07:5分钟实现文件归类助手【实战】
前端·javascript·后端
念念不忘 必有回响2 小时前
viepress:vue组件展示和源码功能
前端·javascript·vue.js
C澒2 小时前
多场景多角色前端架构方案:基于页面协议化与模块标准化的通用能力沉淀
前端·架构·系统架构·前端框架