import { Injectable, inject } from '@angular/core';
import { firstValueFrom } from 'rxjs';
import { HttpService } from './http.service';
import { NzMessageService } from 'ng-zorro-antd/message';
interface ApiResponse<T> {
code: number;
message: string;
data: T;
}
interface TestData {
id: number;
name: string;
}
@Injectable({
providedIn: 'root'
})
export class ApiService {
private readonly hs = inject(HttpService);
private readonly message = inject(NzMessageService);
private readonly apiUrl = '/api/';
async getTestData(id: number): Promise<TestData> {
const url = this.apiUrl + 'testData?id=' + id;
const res = await firstValueFrom(this.hs.get<ApiResponse<TestData>>(url));
return this.getResult(res);
}
async downloadTestFile(params: Record<string, unknown>): Promise<string> {
const url = this.apiUrl + 'testFile';
const blob = await firstValueFrom(this.hs.postBlob(url, params));
return URL.createObjectURL(blob);
}
private getResult<T>(res: ApiResponse<T>): T {
if (res.code === 0) {
return res.data;
}
this.message.error(res.message);
throw new Error(res.message);
}
}