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!');	
    }
  );
相关推荐
报错小能手7 小时前
计算机网络自顶向下方法11——应用层 详解HTTP/3
网络协议·计算机网络·http
游戏开发爱好者87 小时前
Fiddler抓包实战教程 从安装配置到代理设置,详解Fiddler使用方法与调试技巧(HTTPHTTPS全面指南)
前端·测试工具·小程序·https·fiddler·uni-app·webview
universe_017 小时前
前端八股之HTTP
前端·网络协议·http
技术砖家--Felix9 小时前
Spring Boot Web开发篇:构建RESTful API
前端·spring boot·restful
yume_sibai10 小时前
TS 常用内置方法
前端·javascript·typescript
新知图书10 小时前
ArkTS语言、基本组成与数据类型
前端·javascript·typescript
嘗_10 小时前
手写自己的小型react
前端·javascript·react.js
嘀咕博客10 小时前
h5游戏免费下载:HTML5拉杆子过关小游戏
前端·游戏·html5
Moonbit10 小时前
MoonBit 推出 LLVM Debugger,核心用户数破十万
前端·编程语言·llvm