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

相关内容

热门资讯

透视肯定!wepoker轻量版... 透视肯定!wepoker轻量版透视(透视)原来存在有辅助平台(有挂透视)-哔哩哔哩wepoker轻量...
解密透视!wepoker辅助器... 解密透视!wepoker辅助器怎么弄!教学盘点辅助脚本(有挂功能)-哔哩哔哩1、完成wepoker辅...
了解透视!wepoker有没有... 了解透视!wepoker有没有挂!重大来袭辅助攻略(有挂存在)-哔哩哔哩1、每一步都需要思考,不同水...
玩家交流!wepoker线上大... 玩家交流!wepoker线上大神,心悦俱乐部游戏辅助,确实真的是有辅助下载(有挂方式)小薇(辅助器软...
透视ai代打!佛手大菠萝辅助(... 透视ai代打!佛手大菠萝辅助(透视)原来存在有辅助软件(有挂教学)-哔哩哔哩佛手大菠萝辅助是不是有人...
教你透视!aapoker如何设... 教你透视!aapoker如何设置胜率!带你了解辅助攻略(有挂猫腻)-哔哩哔哩1、超多福利:超高返利,...
分享认知!htx矩阵wepok... 分享认知!htx矩阵wepoker辅助,pokemmo手机脚本辅助器,本来是真的有辅助神器(了解有挂...
据了解!来玩app破解(透视)... 据了解!来玩app破解(透视)都是真的有辅助神器(有人有挂)-哔哩哔哩1、在来玩app破解插件功能辅...
专业透视!竞技联盟辅助!202... 专业透视!竞技联盟辅助!2024教程辅助神器(有挂秘籍)-哔哩哔哩1、首先打开竞技联盟辅助辅助器下载...
推荐十款!WePOker有没有... 推荐十款!WePOker有没有透视方法,家乡大二辅助,好像存在有辅助插件(详细教程)一、家乡大二辅助...