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

相关内容

热门资讯

不少玩家反映!智星菠萝辅助,微... 不少玩家反映!智星菠萝辅助,微乐老友广东辅助器(透视)好像是有方法(哔哩哔哩)1)微乐老友广东辅助器...
重大消息!约局吧如何查看是否有... 重大消息!约局吧如何查看是否有挂,微信微乐辅助器使用教程(透视)竟然有有插件(哔哩哔哩)1、点击下载...
推荐攻略!拱趴大菠萝怎么开挂,... 推荐攻略!拱趴大菠萝怎么开挂,微信微乐挂有没有(透视)本来是真的有app(哔哩哔哩)微信微乐挂有没有...
玩家必看科普!xpoker透视... 玩家必看科普!xpoker透视辅助,微乐自建房辅助软件如何下载(透视)切实是真的有技巧(哔哩哔哩)1...
玩家亲测!哈糖大菠萝怎么开挂,... 玩家亲测!哈糖大菠萝怎么开挂,微乐自建房插件详细教程(透视)好像真的有器(哔哩哔哩)1、操作简单,无...
盘点几款!哈糖大菠萝有挂吗5个... 盘点几款!哈糖大菠萝有挂吗5个常用方法,微乐陕西小程序破解器(透视)都是存在有软件(哔哩哔哩)1、金...
有玩家发现!竞技联盟破解版最新... 有玩家发现!竞技联盟破解版最新版,微乐家乡官方app下载(透视)总是存在有技巧(哔哩哔哩)1、实时微...
玩家必看教程!!we poke... 玩家必看教程!!we poker免费辅助器,微乐自建房黑科技辅助工具下载(透视)总是是有软件(哔哩哔...
专业讨论!!哈糖大菠萝有挂吗5... 专业讨论!!哈糖大菠萝有挂吗5个常用方法,微乐小程序免费黑科技下载方法(透视)一直真的是有脚本(哔哩...
必看攻略!德州真人透视脚本,微... 必看攻略!德州真人透视脚本,微信小程序微乐辅助免费版(透视)其实是真的有挂(哔哩哔哩)1、微信小程序...