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

相关推荐
七淮14 分钟前
Next.js SEO 优化完整方案
前端·next.js
e***193521 分钟前
爬虫学习 01 Web Scraper的使用
前端·爬虫·学习
aircrushin25 分钟前
TRAE SOLO 中国版,正式发布!AI 编程的 "Solo" 时代来了?
前端·人工智能
最初的黄昏25 分钟前
flutter 集成flutter_Boost
前端
有意义29 分钟前
JavaScript 词法作用域与闭包:从底层原理到实战理解
前端·javascript·面试
GYY_y37 分钟前
封装一个支持动态表头与权限控制的通用 VxeTable 组件
前端
某只天落42 分钟前
Vue2 通用文件在线预览下载组件:一站式解决多类型文件处理需求(支持视频、文档、图片、Office)
前端
AY呀42 分钟前
黑马喽大闹天宫与JavaScript的寻亲记:作用域与作用域链全解析
前端·javascript·面试
金融数据出海43 分钟前
日本股票市场渲染 KlineCharts K 线图
前端·后端
是Yu欸1 小时前
DevUI MateChat 技术演进:UI 与逻辑解耦的声明式 AI 交互架构
前端·人工智能·ui·ai·前端框架·devui·metachat