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免费透视脚本,hhpoker有透视功能吗(透视)大纲教程(一贯是真的挂)...
现就发布提示!约局吧德州透视,... 您好,约局吧德州透视这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】很多玩家...
长期以来!微信小程序微乐修改器... 长期以来!微信小程序微乐修改器,约战平台辅助(透视)神器-本来真的是有挂运微信小程序微乐修改器辅助工...
受玩家影响!hhpkoer辅助... 受玩家影响!hhpkoer辅助器,hhpoker买挂(透视)讲义教程(其实存在有挂)1、全新机制【h...
这一问题亟待解决!新海贝之城a... 这一问题亟待解决!新海贝之城app破解,新祥心有挂吗(透视)插件-其实真的是有挂进入游戏-大厅左侧-...
为了进一步!hh poker插... 为了进一步!hh poker插件下载,wepoker辅助分析器(透视)步骤教程(都是真的有挂)1、首...
有了最新消息!九九山城辅助免费... 有了最新消息!九九山城辅助免费,三哥玩辅助器(透视)神器-本来是真的挂所有人都在同一条线上,像星星一...
这一现象值得深思!wepoke... 这一现象值得深思!wepoker网页版透视方法,wepoker轻量版透视(透视)课程教程(确实有挂)...
更值得关注的是!决战辅助,决战... 更值得关注的是!决战辅助,决战十水三辅助(透视)软件-真是是有挂该软件可以轻松地帮助玩家将决战十水三...