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

相关推荐
林恒smileZAZ3 小时前
Vue<前端页面版本检测>
前端·javascript·vue.js
码事漫谈6 小时前
当AI开始“思考”:我们是否真的准备好了?
前端·后端
许杰小刀7 小时前
ctfshow-web文件包含(web78-web86)
android·前端·android studio
我是Superman丶7 小时前
Element UI 表格某行突出悬浮效果
前端·javascript·vue.js
恋猫de小郭7 小时前
你的代理归我了:AI 大模型恶意中间人攻击,钱包都被转走了
前端·人工智能·ai编程
xiaokuangren_8 小时前
前端css颜色
前端·css
hoiii1878 小时前
C# 基于 LumiSoft 实现 SIP 客户端方案
前端·c#
anOnion8 小时前
构建无障碍组件之Meter Pattern
前端·html·交互设计
小码哥_常9 小时前
Spring Boot配置diff:解锁配置管理新姿势
前端
小码哥_常9 小时前
告别onActivityResult!Android数据回传的3大痛点与终极解决方案
前端