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

相关内容

热门资讯

透视透视!来玩app破解版(透... 您好,wepoker辅助分析器这款游戏可以开挂的,确实是有挂的,需要了解加去威信【485275054...
昨日!epoker透视,wep... 昨日!epoker透视,wepoker怎么挂飞机(透视)方针教程(一贯是真的挂)wepoker怎么挂...
透视详细!wpk透视是真的吗(... 透视详细!wpk透视是真的吗(透视)wejoker辅助脚本,教程手筋(有挂解密)-哔哩哔哩1、任何w...
此事引发网友热议!sohoo竞... 此事引发网友热议!sohoo竞技联盟辅助器,hhpoker德州透视(透视)学习教程(都是有挂)1、s...
透视专业!we poker辅助... 透视专业!we poker辅助器下载(透视)wejoker开挂,教程学习(有挂猫腻)-哔哩哔哩1、w...
近期!佛手大菠萝辅助,约局吧游... 您好,佛手大菠萝辅助这款游戏可以开挂的,确实是有挂的,需要了解加去威信【485275054】很多玩家...
透视教你!wepoker底牌透... 透视教你!wepoker底牌透视脚本(透视)hhpoker有没有透视挂,教程攻略(有挂实锤)-哔哩哔...
来临!智星德州插件怎么下载,w... 来临!智星德州插件怎么下载,wepoker辅助器下载(透视)教材教程(原来存在有挂)1)智星德州插件...
透视专业!wepoker亲友圈... 透视专业!wepoker亲友圈有用吗(透视)wepoker破解器有用吗,教程绝活儿(有挂秘笈)-哔哩...
迎来新发展!wepoker透视... 迎来新发展!wepoker透视辅助下载,wepoker怎么设置盖牌(透视)手段教程(都是真的是有挂)...