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

相关内容

热门资讯

玩家必备科技!!微信小程序黑科... 玩家必备科技!!微信小程序黑科技(外挂),微信自建房辅助多少钱一个月好像有挂实锤微信小程序黑科技破解...
重大推荐!微信小程序黑科技(外... 重大推荐!微信小程序黑科技(外挂),微乐小程序修复系统有用吗竟然新版有挂微信小程序黑科技破解侠是真的...
推荐一款!!微乐小程序黑科技(... 推荐一款!!微乐小程序黑科技(外挂),微信小程序微乐破解器2025切实的确有挂1、每一步都需要思考,...
研究成果!微信小程序免费黑科技... 研究成果!微信小程序免费黑科技(外挂),微乐小程游戏破解器下载本来揭秘有挂一、微信小程序免费黑科技游...
科普!微信小程序黑科技(外挂)... 科普!微信小程序黑科技(外挂),微乐小程序自建房插件免费一直的确有挂1)微信小程序黑科技免费钻石:进...
玩家必看教程!!微信小程序免费... 玩家必看教程!!微信小程序免费黑科技(外挂),微信小程序怎么开挂切实有挂工具1、在微信小程序免费黑科...
一分钟教你!微信小程序黑科技(... 一分钟教你!微信小程序黑科技(外挂),微乐小程序黑科技下载都是有挂详细1)微信小程序黑科技有没有挂:...
每日必看!微乐小程序免费黑科技... 每日必看!微乐小程序免费黑科技(外挂),广西微乐小程序控制器确实今日头条1、玩家可以在微乐小程序免费...
终于知道!!微乐小程序黑科技(... 终于知道!!微乐小程序黑科技(外挂),贵州微乐自建房辅助软件下载其实有挂辅助1、实时微乐小程序黑科技...
解谜透视!红龙poker辅助器... 解谜透视!红龙poker辅助器免费观看,epoker透视底牌(透视)都是存在有辅助攻略(哔哩哔哩)1...