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

相关内容

热门资讯

透视辅助!德州透视脚本,wep... wepoker高级辅助 无需打开直接搜索微信:136704302本司针对手游进行,选择我们的四大理由...
重大通报“德普之星私人局辅助免... 重大通报“德普之星私人局辅助免费”开挂(透视)辅助神器(攻略方法真的有挂) >>您好:软件加薇136...
透视辅助!竞技联盟辅助插件,w... 透视辅助!竞技联盟辅助插件,wepoker透视脚本是什么,实测开挂辅助神器(透视有挂教学);无需打开...
分辨真假“wepoker辅助工... 分辨真假“wepoker辅助工具”开挂(透视)辅助安装(细节揭秘有人有挂) 了解更多开挂安装加(13...
透视辅助!hhpoker德州机... wepoker破解器激活码开挂教程视频分享装挂详细步骤在当今的网络游戏中,wepoker破解器激活码...
我来教教大家“wepoker怎... 我来教教大家“wepoker怎么设置房间”开挂(透视)辅助安装(科技教程有挂透明挂);无需打开直接搜...
透视辅助!WePOker有没有... 透视辅助!WePOker有没有透视方法,aa poker辅助,通报开挂辅助安装(透视有挂细节);无需...
记者揭秘“哈糖大菠萝有挂吗”开... >>您好:确实是有挂的,很多玩家在这款游戏中打牌都会发现很多用户的牌特别好,总是好牌,而且好像能看到...
透视辅助!德州局脚本,poke... 您好:这款pokemmo脚本手机版游戏是可以开挂的,确实是有挂的,很多玩家在这款pokemmo脚本手...
揭秘真相“wepoker怎么开... 您好:这款游戏是可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会发现很多用户的牌特别好,总是好...