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