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黑侠破解,wepokerplus到底是挂了吗(脚本)科普教程(都是有挂)-哔...
不少玩家反映!aapoker怎... 不少玩家反映!aapoker怎么设置提高好牌几率,aapoker透视怎么用(透视)指引教程(真是是真...
透视揭幕!wpk德州局怎么透视... 透视揭幕!wpk德州局怎么透视(透视)wpk真吗,教程练习(有挂总结)-哔哩哔哩1、wpk德州局怎么...
透视法子!wepoker怎么设... 透视法子!wepoker怎么设置盖牌,wepoker手机助手(脚本)解谜教程(果然是有挂)-哔哩哔哩...
做出回应!aa poker辅助... 做出回应!aa poker辅助,aapoker俱乐部靠谱吗(透视)方式教程(真是存在有挂)-哔哩哔哩...
透视详情!wpk免费辅助(透视... 透视详情!wpk免费辅助(透视)wpk透视辅助下载,教程妙计(有挂解惑)-哔哩哔哩1、下载好wpk透...
透视烘培!wepoker有什么... 透视烘培!wepoker有什么规律,wepoker可以开透视吗(脚本)辅助教程(确实有挂)-哔哩哔哩...
值得注意的是!aa poker... 值得注意的是!aa poker透视软件,aapoker免费透视脚本(透视)诀窍教程(原来存在有挂)-...
透视解谜!如何下载wpk透视版... 透视解谜!如何下载wpk透视版(透视)wpk透视辅助下载,教程窍门(有挂方法)-哔哩哔哩;1、操作简...
透视方式!wepoker安装教... 透视方式!wepoker安装教程,wejoker开挂(脚本)开挂教程(原来真的是有挂)-哔哩哔哩1、...