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底牌透视脚本,微信小程序自建房记牌器,操作教程(有挂方式)-哔哩哔哩;1、w...
总算了解!!欢乐情怀脚本辅助器... 总算了解!!欢乐情怀脚本辅助器ios,wepoker破解器有用吗,步骤教程(有挂方针)-哔哩哔哩1、...
教你透视!uupoker透视,... 教你透视!uupoker透视,hhpoker有没有作必弊辅助,教材教程(有挂透视)-哔哩哔哩1、hh...
揭露透视!德州局透视!切实真的... 揭露透视!德州局透视!切实真的是有辅助软件(有挂教程)-哔哩哔哩1、玩家可以在德州局透视线上大神俱乐...
必备透视!哈糖大菠萝挂,微信小... 必备透视!哈糖大菠萝挂,微信小程序辅助器脚本,手筋教程(有挂教程)-哔哩哔哩1、每一步都需要思考,不...
玩家必看攻略!赣牌圈靠谱吗,s... 玩家必看攻略!赣牌圈靠谱吗,sohoopoker辅助,举措教程(有挂细节)-哔哩哔哩1、每一步都需要...
曝光透视!wpk德州局怎么透视... 曝光透视!wpk德州局怎么透视,佛手大菠萝13道挂哪里,法子教程(有挂攻略)-哔哩哔哩佛手大菠萝13...
总结透视!哈糖大菠萝万能挂!原... 总结透视!哈糖大菠萝万能挂!原来一直都是有辅助神器(有挂教程)-哔哩哔哩1、哈糖大菠萝万能挂辅助软件...
推荐透视!aapoker怎么拿... 推荐透视!aapoker怎么拿好牌,微乐自建房辅助工具官网,技法教程(有挂猫腻)-哔哩哔哩1、aap...
查到实测辅助!心悦辅助器,po... 查到实测辅助!心悦辅助器,pokemmo手机脚本,指南教程(有挂解惑)-哔哩哔哩;pokemmo手机...