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

相关内容

热门资讯

透视透视!德州私人局脚本(透视... 【福星临门,好运相随】;透视透视!德州私人局脚本(透视)底牌透视挂辅助神器(可靠开挂辅助德州教程)-...
2分钟了解!传送屋激k辅助器(... 2分钟了解!传送屋激k辅助器(辅助挂)详细透视开挂辅助第三方教程(一贯是有挂)-哔哩哔哩;一、传送屋...
推荐一款!"德扑之星... 推荐一款!"德扑之星辅牌器靠谱"详细外挂透明挂辅助软件-素来是真的有挂(哔哩哔哩)是一款可以让一直输...
2分钟了解(德州wepower... 2分钟了解(德州wepower)软件透明挂辅助代打(透视)科技教程(2022已更新)(哔哩哔哩);1...
透视代打!wepoker私人局... 透视代打!wepoker私人局辅助(透视)底牌透视挂辅助程序(可靠开挂辅助AI教程)-哔哩哔哩;1....
第7分钟了解!决战十三水辅助挂... 第7分钟了解!决战十三水辅助挂码(辅助挂)详细透视开挂辅助安装教程(本来是有挂)-哔哩哔哩;决战十三...
必备科技"wpk辅助... 必备科技"wpk辅助器安装"详细外挂透明挂辅助神器-从前存在有挂(哔哩哔哩);相信小伙伴都知道这个w...
七分钟了解(wepoke有挂)... 七分钟了解(wepoke有挂)黑科技透明挂辅助神器(透视)安装教程(2022已更新)(哔哩哔哩);w...
透视教程!wepoker安装教... 透视教程!wepoker安装教程(透视)底牌透视挂辅助神器(可靠开挂辅助攻略方法)-哔哩哔哩是一款可...
六分钟了解!神武4辅助脚本(辅... 六分钟了解!神武4辅助脚本(辅助挂)详细透视开挂辅助软件教程(好像是有挂)-哔哩哔哩;神武4辅助脚本...