fork of hey-api/openapi-ts because I need some additional things
1import type { HttpErrorResponse } from '@angular/common/http';
2import { HttpClient } from '@angular/common/http';
3import { Component, inject, signal } from '@angular/core';
4
5import type { AddPetErrors, Pet } from '../../client';
6import { PetService } from '../../client';
7import { createClient } from '../../client/client';
8
9const localClient = createClient({
10 // set default base url for requests made by this client
11 baseUrl: 'https://petstore3.swagger.io/api/v3',
12 /**
13 * Set default headers only for requests made by this client. This is to
14 * demonstrate local clients and their configuration taking precedence over
15 * internal service client.
16 */
17 headers: {
18 Authorization: 'Bearer <token_from_local_client>',
19 },
20});
21
22@Component({
23 host: { ngSkipHydration: 'true' },
24 imports: [],
25 selector: 'app-demo',
26 styleUrl: './demo.css',
27 templateUrl: './demo.html',
28})
29export class Demo {
30 pet = signal<Pet | undefined>(undefined);
31 error = signal<
32 | undefined
33 | {
34 error: AddPetErrors[keyof AddPetErrors] | Error;
35 response: HttpErrorResponse;
36 }
37 >(undefined);
38
39 #petService = inject(PetService);
40 #http = inject(HttpClient);
41
42 // // you can set a global httpClient for this client like so, in your app.config, or on each request (like below)
43 // ngOnInit(): void {
44 // localClient.setConfig({
45 // httpClient: this.#http,
46 // });
47 // }
48
49 onGetPetByIdLocalClient = async () => {
50 const { data, error, response } = await this.#petService.getPetById({
51 client: localClient,
52 httpClient: this.#http,
53 path: {
54 // random id 1-10
55 petId: Math.floor(Math.random() * (10 - 1 + 1) + 1),
56 },
57 });
58
59 if (error) {
60 console.log(error);
61 this.error.set({
62 error,
63 response: response as HttpErrorResponse,
64 });
65 return;
66 }
67
68 this.pet.set(data);
69 this.error.set(undefined);
70 };
71
72 onGetPetById = async () => {
73 const { data, error, response } = await this.#petService.getPetById({
74 path: {
75 // random id 1-10
76 petId: Math.floor(Math.random() * (10 - 1 + 1) + 1),
77 },
78 });
79
80 if (error) {
81 console.log(error);
82 this.error.set({
83 error,
84 response: response as HttpErrorResponse,
85 });
86 return;
87 } else {
88 console.log(error);
89 console.log(response);
90 this.pet.set(data);
91 this.error.set(undefined);
92 }
93 };
94}