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、完成微信闲来辅助神器...
科技分享!wepoker怎么拿... 科技分享!wepoker怎么拿到好牌,大唐麻将开挂软件,举措教程(揭秘有挂)1、玩家可以在大唐麻将开...
值得注意的是!线上德州的辅助器... 值得注意的是!线上德州的辅助器是什么,逗娱碰胡开挂,指南书教程(有挂猫腻)1)逗娱碰胡开挂有没有挂:...
分享认知!epoker免费透视... 分享认知!epoker免费透视脚本,微乐小程序辅助开发,方针教程(有挂功能)微乐小程序辅助开发是不是...
为切实保障!wepoker透视... 为切实保障!wepoker透视底牌脚本,福建13水软件辅助,法门教程(的确有挂)1.福建13水软件辅...
据公告内容!约局吧德州真的存在... 据公告内容!约局吧德州真的存在透视吗,天道手游辅助,手册教程(有挂详情)1、用户打开应用后不用登录就...
科技通报!wepoker游戏下... 科技通报!wepoker游戏下载,免费挂机辅助工具,手册教程(有挂教学)1、操作简单,无需免费挂机辅...
今日科普!wepoker底牌透... 今日科普!wepoker底牌透视脚本,微信小程序多乐辅助器,大纲教程(有挂技巧)1.微信小程序多乐辅...
事发当天!德州透视hhpoke... 事发当天!德州透视hhpoker,微信呢途游四川辅助器,绝活教程(有挂详细)1、玩家可以在微信呢途游...
分享一款!hhpoker德州挂... 分享一款!hhpoker德州挂真的有吗,杭州都莱有没有挂,窍门教程(有挂详细);杭州都莱有没有挂能透...