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

相关内容

热门资讯

一分钟教你!(德州wepowe... 《一分钟教你!(德州wepower)外挂软件透明挂辅助脚本!(wepoke游戏数据有说法)揭秘攻略(...
第8分钟透明挂!hhpoker... 第8分钟透明挂!hhpoker透视脚本视频,wepoker脚本下载(透视)2025新版总结(有挂助手...
发现一款!wepokeai辅助... 发现一款!wepokeai辅助,德州之星辅助挂,2025教程(有挂规律)-哔哩哔哩;德州之星辅助挂A...
黑科技新版!(WPK教程)外挂... 黑科技新版!(WPK教程)外挂软件透明挂辅助app!(wepoke辅助工具的使用教程)大神讲解(20...
第四分钟知晓!wepoker网... 第四分钟知晓!wepoker网页版透视方法,htx矩阵wepoker辅助(透视)大神讲解(有挂解密)...
揭秘攻略!微扑克ai辅助器下载... 揭秘攻略!微扑克ai辅助器下载,微扑克辅助软件下载,技巧教程(有挂技巧)-哔哩哔哩;微扑克辅助软件下...
透视计算!(微扑克ai)外挂透... 透视计算!(微扑克ai)外挂透视透明挂辅助插件!(wepoke软件透明下载渠道)插件教程(2024已...
第五分钟普及!德普之星透视辅助... 第五分钟普及!德普之星透视辅助软件激活码,pokemmo脚本辅助器下载(透视)wpk教程(有挂细节)...
揭秘真相!aapoker辅助软... 【福星临门,好运相随】;揭秘真相!aapoker辅助软件,微扑克有辅助挂,科技教程(有挂细节)-哔哩...
安装程序教程!(wpk安卓)外... 安装程序教程!(wpk安卓)外挂透明挂辅助透视!(aapoker有可以规律)2025新版总结(202...