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底牌透视,菠萝德普辅助器免费版在哪里,手筋教程(真的有挂)-哔哩哔哩菠萝德普...
必看攻略!!熊猫辅助器视频教程... 必看攻略!!熊猫辅助器视频教程,pokemmo脚本最新版,诀窍教程(今日头条)-哔哩哔哩1、熊猫辅助...
解迷透视!德普之星有透视辅助吗... 解迷透视!德普之星有透视辅助吗,wepoker怎么挂底牌,方针教程(有挂讲解)-哔哩哔哩1.德普之星...
一分钟揭秘!微乐自建房脚本免费... 一分钟揭秘!微乐自建房脚本免费下载,hhpoker透视工具,技法教程(有挂实锤)-哔哩哔哩1、金币登...
有挂透视!wepoker有人用... 有挂透视!wepoker有人用过吗,智星菠萝有挂吗,技法教程(有挂透明挂)-哔哩哔哩1、wepoke...
玩家必知教程!!微信微乐开挂,... 玩家必知教程!!微信微乐开挂,哈糖大菠萝万能挂,资料教程(有挂细节)-哔哩哔哩1、哈糖大菠萝万能挂脚...
解谜透视!佛手在线是不是有挂,... 解谜透视!佛手在线是不是有挂,德普之星app安卓版破解版,资料教程(存在有挂)-哔哩哔哩亲,关键说明...
科普分享!赣牌圈的好牌几率,佛... 科普分享!赣牌圈的好牌几率,佛手大菠萝13道挂哪里,指引教程(有挂详细)-哔哩哔哩1、首先打开佛手大...
专业透视!wepoker怎么开... 专业透视!wepoker怎么开辅助,拱趴游戏破解器,窍要教程(有挂分享)-哔哩哔哩1、上手简单,内置...
大家学习交流!罗松十三道辅助器... 大家学习交流!罗松十三道辅助器,wpk安卓下载辅助,演示教程(有挂助手)-哔哩哔哩1、罗松十三道辅助...