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

相关内容

热门资讯

新版黑科技!governoro... 新版黑科技!governorofpoker3有挂吗(透视)太坑了真的是有挂(曝光教程黑科技攻略)1、...
第一分钟黑科技!wepoke透... 第一分钟黑科技!wepoke透明黑科技,德州nzt实战,安装教程(有挂黑科技)1、不需要AI权限,帮...
黑科技辅助挂!aapoker下... 黑科技辅助挂!aapoker下载教程(WepokE)外挂透视辅助挂(详细说明黑科技技巧);小薇(透视...
规律黑科技!德州ai辅助有用吗... 规律黑科技!德州ai辅助有用吗(透视)太坑了是真的有挂(2025新版技巧黑科技插件)1、德州ai辅助...
八分钟黑科技!微扑克的辅助工具... 八分钟黑科技!微扑克的辅助工具苹果,微扑克wpk辅助存在吗,必备教程(有挂黑科技);玩家必备必赢加哟...
黑科技代打!微扑克有机器人吗(... 黑科技代打!微扑克有机器人吗(WepOke)外挂黑科技辅助插件(玩家必看教程黑科技透视);建议优先通...
透明挂黑科技!轰趴十三水有后台... 透明挂黑科技!轰趴十三水有后台吗(透视)太坑了是有挂(可靠教程黑科技脚本)1、轰趴十三水有后台吗ai...
第9分钟黑科技!wpk有长期盈... 《第9分钟黑科技!wpk有长期盈利玩家吗,wpk透视辅助测试,2025新版技巧(有挂黑科技)》 wp...
黑科技软件!红龙扑克是真是假(... 黑科技软件!红龙扑克是真是假(wePOke)外挂透视辅助软件(揭秘关于黑科技方法);人气非常高,ai...
工具黑科技!wepoke软件靠... 工具黑科技!wepoke软件靠谱吗(透视)太坑了是真的有挂(德州教程黑科技解密);1、进入游戏-大厅...