angular入门基础教程(十一)与服务端数据交互

前后端分离开发,少不了与后端进行数据接口的对接,在vue,react中我们要借助第三方的axios来进行数据请求。在ng中,为我们封装了了一层httpClient,我们直接使用即可

依赖注入

我们需要再次封装一次

js 复制代码
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');
  }
}

组件中使用

依赖注入,我们封装好了的接口方法

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

相关推荐
艾小码5 分钟前
从写原生JS到玩转框架:我走过的那些弯路和顿悟时刻
前端·javascript
初遇你时动了情4 小时前
css中backdrop-filter 详细使用 ios毛玻璃效果、filter和backdrop-filter使用说明
前端·css
景彡先生5 小时前
Python Selenium详解:从入门到实战,Web自动化的“瑞士军刀”
前端·python·selenium
Liudef067 小时前
DeepseekV3.2 实现构建简易版Wiki系统:从零开始的HTML实现
前端·javascript·人工智能·html
景早8 小时前
vue 记事本案例详解
前端·javascript·vue.js
wangjialelele9 小时前
Qt中的常用组件:QWidget篇
开发语言·前端·c++·qt
乔冠宇10 小时前
vue需要学习的点
前端·vue.js·学习
用户479492835691510 小时前
同样是 #,锚点和路由有什么区别
前端·javascript
Hero_112710 小时前
在pycharm中install不上需要的包
服务器·前端·pycharm
爱上妖精的尾巴10 小时前
5-26 WPS JS宏数组元素添加删除应用
开发语言·前端·javascript·wps·js宏