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

相关推荐
新知图书15 分钟前
12.3 智能体中Skill的约束与自进化实战
java·前端·数据库
风月说与山鬼18 分钟前
四、Tailwind CSS——间距与尺寸
前端·css·tailwind css
en.en..24 分钟前
C语言 static函数与头文件封装规范
java·c语言·前端
计算机魔术师28 分钟前
旅途中用手机远程控制电脑?电脑不在身边,ToDesk/UU远程/TeamViewer移动端深度实测
前端
风月说与山鬼42 分钟前
三、Tailwind CSS——排版与文字样式
前端·css·tailwind css
eokred1 小时前
图片预览组件的另一种设计:Headless、可组合、开箱即用
前端·react
南雨北斗1 小时前
解决web开发中前后端跨域通信(session失效问题)
前端
Y3815326621 小时前
body-upload-js
前端·javascript·浏览器·深拷贝·数据克隆
Apifox1 小时前
Apifox 8 月更新|调试、权限与协作体验持续优化
前端·后端·测试