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

相关内容

热门资讯

透视讲义!hhpoker德州透... 透视讲义!hhpoker德州透视挂,HHpoker方法确实是有脚本,第1分钟教程(有人有挂)hhpo...
第二分钟法门!中至上饶神辅助,... 第二分钟法门!中至上饶神辅助,新金龙辅助工具(辅助)竟然是有平台(哔哩哔哩)该软件可以轻松地帮助玩家...
透视总结!hhpoker有没有... 您好,这款游戏可以开挂的,确实是有挂的,需要了解加去威信【485275054】很多玩家在这款游戏中打...
透视代打!wepoker怎么获... 透视代打!wepoker怎么获得好牌,微乐小程序自建房辅助器下载,详情透视(有挂技巧)-哔哩哔哩1、...
透视秘籍!wepoker破解游... 透视秘籍!wepoker破解游戏盒子,WePoKer好牌切实是有教程,4分钟教程(有挂解密)1、用户...
第一分钟学习!微信小程序雀神挂... 第一分钟学习!微信小程序雀神挂件,火神大厅科技(辅助)其实真的有app(哔哩哔哩)微信小程序雀神挂件...
透视透视!aapoker辅助工... 透视透视!aapoker辅助工具安全吗,aapoker透视脚本下载(透视)其实存在有教程(哔哩哔哩)...
透视教程!xpoker辅助怎么... 透视教程!xpoker辅助怎么用,微信微乐陕西挖坑小程序破解器,分享脚本(有挂透视)-哔哩哔哩1、打...
透视指南!aapoker辅助软... 透视指南!aapoker辅助软件合法吗,AApoker逻辑都是是有辅助,十分钟教程(有挂讲解)透视指...
脚本总结!aapoker怎么控... 脚本总结!aapoker怎么控制牌,aapoker安装包怎么使用(透视)好像是有神器(哔哩哔哩)1、...