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

相关内容

热门资讯

透视演示!hh poker透视... 您好,hh poker透视器下载这款游戏可以开挂的,确实是有挂的,需要了解加去威信【13670430...
透视办法!hhpoker有没有... 透视办法!hhpoker有没有作必弊挂,hh poker插件下载(透视)好像真的是有脚本脚本(哔哩哔...
透视指南书!aapoker如何... 透视指南书!aapoker如何设置胜率,aapoker怎么提高中牌率(透视)果然存在有脚本神器(哔哩...
透视法子!aapoker能控制... 透视法子!aapoker能控制牌吗,aapoker怎么拿好牌(透视)竟然是真的脚本攻略(哔哩哔哩)1...
透视法门!hhpoker辅助挂... 透视法门!hhpoker辅助挂,hhpoker智能辅助插件(透视)原来是有脚本软件(哔哩哔哩)1、全...
透视绝活儿!德普之星辅助工具如... 透视绝活儿!德普之星辅助工具如何打开,德扑之心免费透视(透视)竟然是真的透视攻略(哔哩哔哩)1、许多...
透视阶段!aapoker发牌逻... 透视阶段!aapoker发牌逻辑,aapoker怎么拿好牌(透视)确实有透视神器(哔哩哔哩)aapo...
透视手段!wpk透视怎么安装,... 透视手段!wpk透视怎么安装,wpk模拟器是什么(透视)确实真的是有脚本软件(哔哩哔哩)1、许多玩家...
透视方案!wpk透视工作室,w... 透视方案!wpk透视工作室,wpk辅助器(透视)其实存在有透视脚本(哔哩哔哩)一、wpk透视工作室可...
透视项目!hhpoker为什么... 透视项目!hhpoker为什么一直输,hhpoker哪个俱乐部靠谱(透视)总是存在有透视挂(哔哩哔哩...