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

相关内容

热门资讯

透视教程!hhpoker怎么开... 透视教程!hhpoker怎么开透视,werplan怎么透视,攻略教程(确实有挂)-哔哩哔哩1、hhp...
第四分钟科普!wepoker免... 第四分钟科普!wepoker免费脚本咨询(透视)总是是真的挂,AI教程(有挂总结)-哔哩哔哩1、完成...
透视肯定!hhpoker德州挂... 透视肯定!hhpoker德州挂真的有吗(透视)好像是有挂,2025新版教程(有挂计算器)-哔哩哔哩一...
透视新版!wpk私人辅助,wp... 透视新版!wpk私人辅助,wpk有那种辅助吗,模板教程(有挂教程)-哔哩哔哩小薇(透视辅助)致您一封...
第1分钟外挂!hhpoker真... 第1分钟外挂!hhpoker真的假的(透视)切实是有挂,实用技巧(有挂方式)-哔哩哔哩1、进入游戏-...
透视游戏!wpk免费辅助(透视... 透视游戏!wpk免费辅助(透视)都是真的有挂,新2025版(有挂网页版)-哔哩哔哩1、玩家可以在wp...
透视游戏!aapoker插件下... 透视游戏!aapoker插件下载,福建大菠萝万能辅助器,诀窍教程(的确有挂)-哔哩哔哩1、福建大菠萝...
5分钟开挂!wepokerpl... 5分钟开挂!wepokerplus开挂(透视)好像存在有挂,切实教程(有挂解惑)-哔哩哔哩wepok...
透视辅助!wepoker怎么破... 透视辅助!wepoker怎么破解游戏(透视)一直真的是有挂,必胜教程(有挂科技)-哔哩哔哩wepok...
透视软件!wepoker免费脚... 透视软件!wepoker免费脚本咨询,wpk免费辅助,窍要教程(有挂详细)-哔哩哔哩1、每一步都需要...