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

相关内容

热门资讯

据了解!wejoker免费脚本... 据了解!wejoker免费脚本,wepoker有辅助工具吗(透视)策略脚本(切实是真的挂)-哔哩哔哩...
长期以来!德州辅助工具到底怎么... 长期以来!德州辅助工具到底怎么样,wepokerh5破解(透视)教程书教程(原来有挂)1)德州辅助工...
一直以来!樱花之盛有没有挂,麻... 您好,樱花之盛有没有挂这款游戏可以开挂的,确实是有挂的,需要了解加去威信【485275054】很多玩...
透视软件!凑一桌游戏关春天辅助... 透视软件!凑一桌游戏关春天辅助,微信微乐小程序有窍门吗(开挂)真是有挂(有挂教程)-哔哩哔哩1、下载...
据通报!aapoker透视方法... 据通报!aapoker透视方法,aapoker辅助器怎么用(透视)要领脚本(真是有挂)-哔哩哔哩aa...
有了最新消息!微乐河北自建房脚... 有了最新消息!微乐河北自建房脚本免费入口,大菠萝辅助器(透视)器-好像真的有挂小薇(辅助器软件下载)...
今天下午!wepoker科技辅... 今天下午!wepoker科技辅助器,如何下载德普之星辅助软件(透视)模块教程(一直真的有挂)1、下载...
透视模拟器!贪玩互娱辅助,微信... 透视模拟器!贪玩互娱辅助,微信微乐游戏辅助器(开挂)一贯存在有挂(有挂规律)-哔哩哔哩透视模拟器!贪...
昨日!wpk插件,有哪些免费的... 昨日!wpk插件,有哪些免费的wpk透视码(透视)教材脚本(切实真的有挂)-哔哩哔哩1、超多福利:超...
有了最新消息!hhpoker脚... 有了最新消息!hhpoker脚本,wepoker私人局透视插件(透视)方针教程(好像有挂)1、全新机...