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

相关内容

热门资讯

透视软件!哈糖大菠萝万能挂(透... 透视软件!哈糖大菠萝万能挂(透视)底牌透视挂辅助程序(可靠开挂辅助必赢教程)-哔哩哔哩;1、超多福利...
透视工具!wepoker破解工... 透视工具!wepoker破解工具,威信茶馆透视挂,力荐教程(有挂细节)-哔哩哔哩1、起透看视 威信茶...
九分钟了解!微乐家乡麻将挂(辅... 九分钟了解!微乐家乡麻将挂(辅助挂)最初真的是有挂(专业辅助分享教程)-哔哩哔哩;最新版2026是一...
黑科技辅助!wpk发牌可以这离... 黑科技辅助!wpk发牌可以这离谱(智能ai辅助插件安装)软件透明挂黑科技(本来是真的有挂)-哔哩哔哩...
透视实锤!wepoker透视是... 您好:wepoker透视是真的这款游戏可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会发现很多...
透视美元局!wepokerpl... 透视美元局!wepokerplus开挂,武陵游辅助器,线上教程(有挂猫腻)-哔哩哔哩1、下载好武陵游...
黑科技辅助!德州ai辅助外挂(... 黑科技辅助!德州ai辅助外挂(智能ai辅助工具)软件透明挂黑科技(一直有挂)-哔哩哔哩;德州ai辅助...
第九分钟了解!五彩茶馆有挂(辅... 第九分钟了解!五彩茶馆有挂(辅助挂)从前是真的有挂(专业辅助必胜教程)-哔哩哔哩;是一款可以让一直输...
透视挂透视!德州局透视脚本(透... 透视挂透视!德州局透视脚本(透视)底牌透视挂辅助插件(可靠开挂辅助安装教程)-哔哩哔哩相信很多朋友都...
透视挂!wepoker透视方法... 透视挂!wepoker透视方法,微乐春天小程序辅助,必胜教程(有挂解惑)-哔哩哔哩1、完成微乐春天小...