angular入门基础教程(十一)与服务端数据交互

前后端分离开发,少不了与后端进行数据接口的对接,在vue,react中我们要借助第三方的axios来进行数据请求。在ng中,为我们封装了了一层httpClient,我们直接使用即可

依赖注入

我们需要再次封装一次

js 复制代码
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root',
})
export class HttpService {
  constructor(private http: HttpClient) {
    this.http = http;
  }

  getData() {
    return this.http.get('https://xxxxxxxxxx');
  }
}

组件中使用

依赖注入,我们封装好了的接口方法

js 复制代码
import { Component, inject } from '@angular/core';
import { HttpService } from '../../services/http.service';
import { firstValueFrom } from 'rxjs';
@Component({
  selector: 'app-about',
  standalone: true,
  imports: [FormsModule, UpperCasePipe],
  templateUrl: './about.component.html',
  styleUrl: './about.component.css',
})
export class AboutComponent {

  dataLists: any = [];
  //依赖注入,我们封装好了的接口方法
  constructor(
    private carServices: CarServiceService,
    private httpService: HttpService
  ) {
  }

  //声明周期
  async ngOnInit() {
    console.log('ngOnInit');
     //将获取接口数据的.subscribe改造成了async await
    const products = await firstValueFrom(this.httpService.getData());
    console.log('🚀 ~ AboutComponent ~ ngOnInit ~ res:', products);
    this.dataLists = products;
  }
}

这样我们就获取到了后端数据

关于httpClient还有很多配置项与其他的几种请求方式,可以参考官网自行测试

相关推荐
linux_cfan1 小时前
17 · 引擎适配器全景:HLS/DASH/Vimeo/Mux/Cast
前端·javascript·音视频
计算机魔术师2 小时前
烧掉2780亿美元还不够?OpenAI的资本豪赌让人头皮发麻
前端
IT_陈寒3 小时前
Java线程池用错参数,我的服务居然悄悄崩溃了
前端·人工智能·后端
卡布鲁3 小时前
React useMemo 与 useCallback 完全指南:原理、场景与避坑
前端·react.js
碳基修炼3 小时前
排查记:本地 devServer 是 http,浏览器却把 302 重定向升级成了 https
前端·http
步行cgn3 小时前
Spring p 命名空间注入详解
java·前端·spring
何何____3 小时前
Vue 生命周期详解
前端·javascript
江米小枣tonylua4 小时前
TypeScript 全面の拥抱 !Prisma 8 + Electron 升级实战
前端
闪耀之光M784 小时前
npm命令解析
前端
咸鱼老弟4 小时前
AI Agent 的"自主性悖论"——为什么给它的自由度越大,越要配一套更硬的护栏
前端·人工智能