我们可以获取API的类型并将其存储在
T
,然后我们基于此配置其余部分
T
如下所示!
import { HttpResponse } from '@angular/common/http';
import { Component } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import { firstValueFrom, Observable } from 'rxjs';
import 'zone.js';
import { ApiService } from './api.service';
export async function baseResponseHandler<T>(
arg: Observable<HttpResponse<T>>
): Promise<T> {
const value = await firstValueFrom(arg); //rxjs Observable -> Promise
if (value.ok) {
return <T>value.body;
}
return <T>value.body;
}
@Component({
selector: 'app-root',
standalone: true,
template: `
<h1>Hello from {{ name }}!</h1>
<a target="_blank" href="https://angular.dev/overview">
Learn more about Angular
</a>
`,
})
export class App {
name = 'Angular';
constructor(private api: ApiService) {}
ngOnInit() {
this.getDummy();
}
async getDummy() {
const response = await baseResponseHandler(
this.api.getAccountInfo('response')
); //response is unknown
console.log(response);
}
}
bootstrapApplication(App);
stackblitz