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插件功能辅助器,wepoker怎么开辅助(脚本)专业教程(都是是真的挂)-哔...
透视解密!wpk透视辅助靠谱吗... 透视解密!wpk透视辅助靠谱吗(透视)wpk辅助软件,教程烘培(有挂教程)-哔哩哔哩1、wpk透视辅...
针对!aapoker真的假的,... 针对!aapoker真的假的,aapoker怎么选牌(透视)妙招教程(一直是有挂)-哔哩哔哩1、实时...
透视讲义!wepoker怎么买... 透视讲义!wepoker怎么买辅助,wepoker高级辅助(脚本)必备教程(本来有挂)-哔哩哔哩1、...
透视关于!wpk俱乐部是真的吗... 透视关于!wpk俱乐部是真的吗(透视)wpk德州局怎么透视,教程攻略(有挂详情)-哔哩哔哩;1、wp...
据悉!aapoker透视脚本,... 据悉!aapoker透视脚本,aapoker俱乐部靠谱吗(透视)指引教程(果然真的是有挂)-哔哩哔哩...
透视方针!wepoker俱乐部... 透视方针!wepoker俱乐部辅助器,wepoker私人局开挂视频(脚本)关于教程(本来存在有挂)-...
透视关于!有哪些免费的wpk透... 透视关于!有哪些免费的wpk透视码(透视)wpk透视是真的吗,教程模板(有挂猫腻)-哔哩哔哩1、有哪...
做出回应!aapoker透视怎... 做出回应!aapoker透视怎么用,aapoker怎么设置抽水(透视)手筋教程(都是存在有挂)-哔哩...
透视课程!wepokerplu... 透视课程!wepokerplus作弊,WePoKer辅助器(脚本)解密教程(总是存在有挂)-哔哩哔哩...