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!');	
    }
  );
相关推荐
袋鱼不重19 小时前
我的神奇同事,AI 用多了居然写了个 Open In Codex
前端·后端·ai编程
Fireworks19 小时前
深入vue3源码解读 -- 1、响应式的基础概念
前端
程序员黑豆19 小时前
JDK 下载安装与配置详细教程
java·前端·ai编程
hunterandroid19 小时前
文件存储:内部存储与外部存储
前端
NorBugs19 小时前
飞机大战 Low 版 (Made in AI)
前端
angerdream20 小时前
Android手把手编写儿童手机远程监控App之agentweb如何实现全屏
前端
星栈20 小时前
10 分钟跑起第一个 Dioxus 应用:`dx` CLI、`rsx!` 和热更新好不好用
前端·rust·前端框架
奋斗吧程序媛20 小时前
补充一个小知识点:有关@click.native
前端·vue.js
触底反弹20 小时前
🚀 手把手用 HTML5 Canvas 从零打造飞机大战游戏,代码全开源!
前端·javascript·canvas
DJ斯特拉21 小时前
axios快速使用
开发语言·前端·javascript