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

相关内容

热门资讯

随着"微扑克微乐辅助... 随着"微扑克微乐辅助"hhpoker可以控制牌吗(切实真的是有辅助神器)-哔哩哔哩在进入hhpoke...
普及透视!hhpoker作比弊... 普及透视!hhpoker作比弊码怎么用,hhpoker有没有外g挂,原来存在有辅助app(哔哩哔哩)...
日前!新玉海楼游戏茶苑,四川途... 日前!新玉海楼游戏茶苑,四川途游破解安装包(好像是真的神器)-哔哩哔哩1、在四川途游破解安装包插件功...
最新消息!九游辅助插件,hhp... 最新消息!九游辅助插件,hhpoker是真的假的(透视)原来有辅助工具(哔哩哔哩)九游辅助插件脚本下...
近期"wepoker... 近期"wepoker免费透视脚本"pokemmo脚本最新版(本来是真的辅助工具)-哔哩哔哩近期"we...
关于透视!wepoker轻量版... 关于透视!wepoker轻量版书签,we poker辅助器,原来一直总是有辅助技巧(哔哩哔哩)小薇(...
出乎意料的是!宜宾微信微乐辅助... 出乎意料的是!宜宾微信微乐辅助小程序,胡乐麻将辅助(确实是有神器)-哔哩哔哩1、在宜宾微信微乐辅助小...
据监测!微乐小程序破解,pok... 据监测!微乐小程序破解,pokermaster脚本(透视)总是是有辅助教程(哔哩哔哩)微乐小程序破解...
透视透视挂"wepo... 透视透视挂"wepoker免费脚本咨询"pokemmo手机辅助软件(果然存在有辅助软件)-哔哩哔哩在...
推荐透视!aapoker万能辅... 推荐透视!aapoker万能辅助器,aapoker透视脚本下载,确实一直都是有辅助软件(哔哩哔哩)1...