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

相关内容

热门资讯

黑科技存在!红龙扑克有没有挂(... 黑科技存在!红龙扑克有没有挂(wepoke)软件透明挂辅助安装(最新技巧黑科技攻略);小薇(透视辅助...
新星游挂多少钱,丽水都莱辅助软... 新星游挂多少钱,丽水都莱辅助软件,aapoker有脚本吗(有挂脚本)1、下载好丽水都莱辅助软件辅助软...
黑科技好牌(wepower辅助... 黑科技好牌(wepower辅助器)外挂透视辅助插件(透视)总是有挂(黑科技方法)1、wepower辅...
实锤黑科技!德扑线上创建房间(... 实锤黑科技!德扑线上创建房间(透视)太坑了是有挂(力荐教程黑科技介绍);1、实时德扑线上创建房间开挂...
黑科技肯定!wpkai辅助(W... 1、黑科技肯定!wpkai辅助(WePoKer)外挂透视辅助app(揭秘黑科技技巧);详细教程。2、...
新二号辅助软件多少钱,神兽互娱... 新二号辅助软件多少钱,神兽互娱辅助免费,wepoker透视脚本免费下载(有挂揭秘)1、新二号辅助软件...
好友黑科技!微扑克规律吗(透视... 好友黑科技!微扑克规律吗(透视)太坑了存在有挂(科技教程黑科技揭秘)1)微扑克规律吗辅助挂:进一步探...
黑科技挂(wepoke用模拟器... 黑科技挂(wepoke用模拟器)外挂透明挂辅助挂(透视)一贯是有挂(黑科技辅助)1、进入到wepok...
黑科技脚本!wepower软件... 黑科技脚本!wepower软件(wePOKE)软件透明挂辅助神器(来一盘黑科技技巧);《WPK辅助透...
新道游游戏辅助器免费版,微信多... 新道游游戏辅助器免费版,微信多乐跑作弊,wpk辅助软件多少钱一个(有挂攻略)1、任何微信多乐跑作弊a...