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有透视吗(透视)手段教程(一直存在有挂)1、...
来临!wejoker开挂,德州... 来临!wejoker开挂,德州透视是真的吗(透视)方案教程(果然存在有挂)1.德州透视是真的吗 选牌...
随着!aapoker怎么设置抽... 随着!aapoker怎么设置抽水,pokernow辅助工具(透视)窍门教程(真是有挂)1、在aapo...
近期!wepoker透视底牌脚... 近期!wepoker透视底牌脚本,wepoker透视挂底牌(透视)阶段教程(一贯是有挂)一、wepo...
记者获悉!wepoker私人局... 记者获悉!wepoker私人局透视方法,hhpoker透视实战视频(透视)步骤教程(一直真的有挂)1...
做出回应!wpk真吗,德州透视... 做出回应!wpk真吗,德州透视脚本(透视)阶段教程(其实存在有挂)1、德州透视脚本脚本辅助下载、德州...
此事备受玩家关注!wepoke... 此事备受玩家关注!wepoker开辅助能查到吗,wepoker免费透视脚本(透视)秘籍教程(总是真的...
突发!德普之星的辅助工具介绍,... 突发!德普之星的辅助工具介绍,aapoker辅助插件工具(透视)秘籍教程(真是是有挂)1、这是跨平台...
现场直击!wepoker私人局... 现场直击!wepoker私人局辅助,pokemmo手机辅助软件(透视)攻略教程(一贯是有挂)小薇(辅...
目前!拱趴大菠萝挂哪里,aap... 目前!拱趴大菠萝挂哪里,aapoker脚本怎么用(透视)办法教程(真是有挂)拱趴大菠萝挂哪里破解侠是...