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

相关内容

热门资讯

透视安装!德州透视竞技联盟,h... 透视安装!德州透视竞技联盟,hhpoker有辅助吗,秘籍教程(竟然真的是有挂)-哔哩哔哩1、用户打开...
透视软件!aapoker能控制... 透视软件!aapoker能控制牌吗(透视)开挂辅助挂(好像存在有挂)-哔哩哔哩亲,关键说明,aapo...
据通报!中至赣牌圈手机辅助,微... 据通报!中至赣牌圈手机辅助,微友助手破解版,技巧教程(切实是有挂)-哔哩哔哩1、该软件可以轻松地帮助...
透视黑科技!wepoker辅助... 透视黑科技!wepoker辅助工具(透视)开挂辅助方法(其实有挂)-哔哩哔哩wepoker辅助工具辅...
透视ai!智星德州可以透视吗,... 透视ai!智星德州可以透视吗,aapoker脚本,阶段教程(好像真的有挂)-哔哩哔哩亲,关键说明,智...
透视ios!werplan有挂... 透视ios!werplan有挂吗(透视)开挂辅助脚本(都是是真的挂)-哔哩哔哩1、werplan有挂...
有消息称!桂林字牌科技免费版,... 有消息称!桂林字牌科技免费版,新玄龙辅助,力荐教程(切实是真的挂)-哔哩哔哩1、起透看视 桂林字牌科...
透视自建房!约局吧德州可以透视... 透视自建房!约局吧德州可以透视吗(透视)开挂辅助软件(确实真的是有挂)-哔哩哔哩小薇(透视辅助)致您...
透视插件!wepoker养号规... 透视插件!wepoker养号规律,德州局hhpoker,操作教程(都是有挂)-哔哩哔哩运wepoke...
迎来新发展!潮汕汇软件辅助,新... 迎来新发展!潮汕汇软件辅助,新星游辅助软件试用版,教你攻略(真是存在有挂)-哔哩哔哩1、迎来新发展!...