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、很好的...
透视指引!hhpoker开挂教... 透视指引!hhpoker开挂教程,hh poker透视器下载(透视)总是是真的脚本器(哔哩哔哩)1、...
透视法门!悦扑克脚本,约局吧透... 透视法门!悦扑克脚本,约局吧透视挂下载(透视)真是存在有透视器(哔哩哔哩)1、每一步都需要思考,不同...
透视方式!aapoker透视脚... 透视方式!aapoker透视脚本下载,aapoker辅助插件工具(透视)果然真的有脚本app(哔哩哔...
透视方针!德州局hhpoker... 透视方针!德州局hhpoker,德州透视插件(透视)原来存在有脚本挂(哔哩哔哩);1、让任何用户在无...
透视烘培!aapoker ai... 透视烘培!aapoker ai插件,aa poker辅助(透视)一贯真的有透视神器(哔哩哔哩)1、下...
透视项目!wepoker透视辅... 透视项目!wepoker透视辅助下载,wepoker怎么增加运气(透视)切实是有脚本app(哔哩哔哩...
透视指引!拱趴大菠萝辅助神器,... 透视指引!拱趴大菠萝辅助神器,拱趴大菠萝作必弊方法(透视)一直真的是有脚本方法(哔哩哔哩)1、让任何...
透视指南!sohoo开挂辅助,... 透视指南!sohoo开挂辅助,智星德州可以透视吗(透视)都是是真的脚本技巧(哔哩哔哩)1、很好的工具...
透视窍要!wepoker到底有... 透视窍要!wepoker到底有没有透视,wepoker作必弊视频(透视)原来是有脚本神器(哔哩哔哩)...