angular入门基础教程(十一)与服务端数据交互
创始人
2024-11-15 19:10:02
0

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

依赖注入

我们需要再次封装一次

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');   } } 

组件中使用

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

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还有很多配置项与其他的几种请求方式,可以参考官网自行测试

相关内容

热门资讯

黑科技存在(aa扑克有外挂)w... 黑科技存在(aa扑克有外挂)we辅助poker往昔存在有挂!太离谱了从来是真的有挂(2026已更新)...
第五分钟了解!wepoke软件... 第五分钟了解!wepoke软件透明功能教程,红龙扑克记牌器,系统教程(今日头条)-哔哩哔哩1、用户打...
黑科技数据(众合推扑克)推扑克... 黑科技数据(众合推扑克)推扑克一贯有挂!太坑了从前是真的有挂(2026已更新)(哔哩哔哩);原来确实...
第七分钟了解!德扑之星ai代打... 第七分钟了解!德扑之星ai代打可靠,娱友乐脚本,AA德州教程(有挂头条)-哔哩哔哩1、超多福利:超高...
黑科技规律(wepoke存在)... 黑科技规律(wepoke存在)wpk德州最初存在有挂!太坑了往昔真的有挂(2024已更新)(哔哩哔哩...
六分钟了解!wepoke黑科技... 六分钟了解!wepoke黑科技靠谱吗,兴动手机麻将助赢神器,力荐教程(确实有挂)-哔哩哔哩1、构建自...
黑科技实锤(德扑ai软件)we... 黑科技实锤(德扑ai软件)wepower德州素来真的是有挂!太嚣张了好像真的是有挂(2020已更新)...
第九分钟了解!wepoke软件... 第九分钟了解!wepoke软件透明挂怎么弄,雀神小程序输赢规律,2025新版教程(今日头条)-哔哩哔...
辅助黑科技(轰趴大菠萝十三水)... 辅助黑科技(轰趴大菠萝十三水)AApOKER总是是有挂!太无语了起初真的是有挂(2020已更新)(哔...
第九分钟了解!wepoke软件... 第九分钟了解!wepoke软件透明挂怎么弄,微信麻将雀神有挂吗,教你教程(有挂工具)-哔哩哔哩1、微...