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模拟器哪个(本来真的是有挂)1、玩家可以在we...
透视ai代打!wepoker免... 透视ai代打!wepoker免费透视脚本(透视)好友局透视(好像真的有挂)1、wepoker免费透视...
透视了解!wpk模拟器(透视)... 透视了解!wpk模拟器(透视)辅助软件(其实是真的有挂)1、下载好wpk模拟器辅助软件之后点击打开,...
透视有挂!德普之星辅助工具如何... 透视有挂!德普之星辅助工具如何打开(透视)透视(果然是有挂)1、让任何用户在无需德普之星辅助工具如何...
透视线上!wepoker透视苹... 透视线上!wepoker透视苹果系统(透视)透视app下载(果然真的有挂)1、完成wepoker透视...
透视辅助!wepoker透视脚... 透视辅助!wepoker透视脚本免费(透视)wepoker怎么增加运气(总是真的是有挂)1)wepo...
透视好友房!wpk作弊(透视)... 透视好友房!wpk作弊(透视)俱乐部辅助器(真是存在有挂)1、下载好wpk作弊辅助软件之后点击打开,...
透视app!如何下载德普之星辅... 透视app!如何下载德普之星辅助软件(透视)透视(真是有挂)暗藏猫腻,小编详细说明如何下载德普之星辅...
透视工具!wepoker买脚本... 透视工具!wepoker买脚本靠谱吗(透视)有透视方法(果然真的是有挂);1、wepoker买脚本靠...
透视美元局!wepokerh5... 透视美元局!wepokerh5破解(透视)wepoker免费脚本咨询(一直真的有挂)1、玩家可以在w...