Search code examples
javascriptangularjhipsteropenapiopenapi-generator

Argument of type 'Observable<Pet>&Observable<HttpResponse<Pet>>&Observable<HttpEvent<Pet>>' is not assignable to 'Observable<HttpResponse<Pet>>'


I am trying to connect the generated openapi-generator angular code with the JHipster CRUD views. I was trying to edit and tailor them together for the Pet entity, however, I get the following error:

"Argument of type 'Observable & Observable<HttpResponse> & Observable<HttpEvent>' is not assignable to parameter of type 'Observable<HttpResponse>'."

JHipster generates entities having models, services, and CRUD operations. The code generated by the OpenAPI generator has just service and model. I am trying to use the model and service from the OpenAPI gen in JHipster template. I have no idea what to change to remove the error. The code from the pet-update-component.ts, where I have problems with petService.updatePet(pet) and petService.addPet(pet):

    import { Component, OnInit } from '@angular/core';
import { HttpResponse } from '@angular/common/http';
import { FormBuilder, Validators } from '@angular/forms';
import { ActivatedRoute } from '@angular/router';
import { Observable } from 'rxjs';
import { finalize, map } from 'rxjs/operators';

import { Pet } from '../pet.model';
//import { PetService } from '../service/pet.service';
import { PetService } from 'build/openapi/api/pet.service';
import { ICategory } from 'app/entities/category/category.model';
import { CategoryService } from 'app/entities/category/service/category.service';
import { PetStatus } from 'app/entities/enumerations/pet-status.model';

@Component({
  selector: 'jhi-pet-update',
  templateUrl: './pet-update.component.html',
})
export class PetUpdateComponent implements OnInit {
  isSaving = false;
  petStatusValues = Object.keys(PetStatus);

  categoriesSharedCollection: ICategory[] = [];

  editForm = this.fb.group({
    id: [],
    petId: [],
    name: [null, [Validators.required]],
    petStatus: [],
    category: [],
  });

  constructor(
    protected petService: PetService,
    protected categoryService: CategoryService,
    protected activatedRoute: ActivatedRoute,
    protected fb: FormBuilder
  ) {}

  ngOnInit(): void {
    this.activatedRoute.data.subscribe(({ pet }) => {
      this.updateForm(pet);

      this.loadRelationshipsOptions();
    });
  }

  previousState(): void {
    window.history.back();
  }

  save(): void {
    this.isSaving = true;
    const pet = this.createFromForm();
    if (pet.id !== undefined) {
      this.subscribeToSaveResponse(this.petService.updatePet(pet));
    } else {
      this.subscribeToSaveResponse(this.petService.addPet(pet));
    }
  }

  trackCategoryById(index: number, item: ICategory): number {
    return item.id!;
  }

  protected subscribeToSaveResponse(result: Observable<HttpResponse<Pet>>): void {
    result.pipe(finalize(() => this.onSaveFinalize())).subscribe({
      next: () => this.onSaveSuccess(),
      error: () => this.onSaveError(),
    });
  }

  protected onSaveSuccess(): void {
    this.previousState();
  }

  protected onSaveError(): void {
    // Api for inheritance.
  }

  protected onSaveFinalize(): void {
    this.isSaving = false;
  }

  protected updateForm(pet: Pet): void {
    this.editForm.patchValue({
      id: pet.id,
      petId: pet.petId,
      name: pet.name,
      petStatus: pet.petStatus,
      category: pet.category,
    });

    this.categoriesSharedCollection = this.categoryService.addCategoryToCollectionIfMissing(this.categoriesSharedCollection, pet.category);
  }

  protected loadRelationshipsOptions(): void {
    this.categoryService
      .query()
      .pipe(map((res: HttpResponse<ICategory[]>) => res.body ?? []))
      .pipe(
        map((categories: ICategory[]) =>
          this.categoryService.addCategoryToCollectionIfMissing(categories, this.editForm.get('category')!.value)
        )
      )
      .subscribe((categories: ICategory[]) => (this.categoriesSharedCollection = categories));
  }

  protected createFromForm(): Pet {
    return {
      ...new Pet(),
      id: this.editForm.get(['id'])!.value,
      petId: this.editForm.get(['petId'])!.value,
      name: this.editForm.get(['name'])!.value,
      petStatus: this.editForm.get(['petStatus'])!.value,
      category: this.editForm.get(['category'])!.value,
    };
  }
}

Here is the code for pet.service:

/**
     * Update an existing pet
     * Update an existing pet by Id
     * @param body Update an existent pet in the store
     * @param observe set whether or not to return the data Observable as the body, response, or events. defaults to returning the body.
     * @param reportProgress flag to report request and response progress.
     */
    public updatePet(body: Pet, observe?: 'body', reportProgress?: boolean): Observable<Pet>;
    public updatePet(body: Pet, observe?: 'response', reportProgress?: boolean): Observable<HttpResponse<Pet>>;
    public updatePet(body: Pet, observe?: 'events', reportProgress?: boolean): Observable<HttpEvent<Pet>>;
    public updatePet(body: Pet, observe: any = 'body', reportProgress: boolean = false ): Observable<any> {

        if (body === null || body === undefined) {
            throw new Error('Required parameter body was null or undefined when calling updatePet.');
        }

        let headers = this.defaultHeaders;

        // authentication (petstore_auth) required
        if (this.configuration.accessToken) {
            const accessToken = typeof this.configuration.accessToken === 'function'
                ? this.configuration.accessToken()
                : this.configuration.accessToken;
            headers = headers.set('Authorization', 'Bearer ' + accessToken);
        }

        // to determine the Accept header
        let httpHeaderAccepts: string[] = [
            'application/xml',
            'application/json'
        ];
        const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts);
        if (httpHeaderAcceptSelected != undefined) {
            headers = headers.set('Accept', httpHeaderAcceptSelected);
        }

        // to determine the Content-Type header
        const consumes: string[] = [
            'application/json',
            'application/xml',
            'application/x-www-form-urlencoded'
        ];
        const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
        if (httpContentTypeSelected != undefined) {
            headers = headers.set('Content-Type', httpContentTypeSelected);
        }

        return this.httpClient.request<Pet>('put',`${this.basePath}/pet`,
            {
                body: body,
                withCredentials: this.configuration.withCredentials,
                headers: headers,
                observe: observe,
                reportProgress: reportProgress
            }
        );
    }

And finally pet.ts:

/**
 * Swagger Petstore - OpenAPI 3.0
 * This is a sample Pet Store Server based on the OpenAPI 3.0 specification.  You can find out more about Swagger at [http://swagger.io](http://swagger.io). In the third iteration of the pet store, we've switched to the design first approach! You can now help us improve the API whether it's by making changes to the definition itself or the code. That way, with time, we can improve the API in general, and expose some of the new features in OAS3. Some useful links: - [The Pet Store repository](https://github.com/swagger-api/swagger-petstore) - [The source API definition for the Pet Store](https://github.com/swagger-api/swagger-petstore/blob/master/src/main/resources/openapi.yaml)
 *
 * OpenAPI spec version: 1.0.11
 * Contact: [email protected]
 *
 * NOTE: This class is auto generated by the swagger code generator program.
 * https://github.com/swagger-api/swagger-codegen.git
 * Do not edit the class manually.
 */
import { Category } from './category';
import { Tag } from './tag';

export interface Pet { 
    id?: number;
    name: string;
    category?: Category;
    photoUrls: Array<string>;
    tags?: Array<Tag>;
    /**
     * pet status in the store
     */
    status?: Pet.StatusEnum;
}
export namespace Pet {
    export type StatusEnum = 'available' | 'pending' | 'sold';
    export const StatusEnum = {
        Available: 'available' as StatusEnum,
        Pending: 'pending' as StatusEnum,
        Sold: 'sold' as StatusEnum
    };
}

If you have any idea on what I should change, what exactly is the problem, or in what way I should approach this, would be super grateful. Thanks!


Solution

  • Okay, so what I did was commenting out methods declarations with Observable<Pet'> and "Observable<HttpEvent<Pet'>>". I have different problems now but at least those are not highlighted in red anymore.

    /**
         * Update an existing pet
         * Update an existing pet by Id
         * @param body Update an existent pet in the store
         * @param observe set whether or not to return the data Observable as the body, response, or events. defaults to returning the body.
         * @param reportProgress flag to report request and response progress.
         */
        //public updatePet(body: Pet, observe?: 'body', reportProgress?: boolean): Observable<Pet>;
        public updatePet(body: Pet, observe?: 'response', reportProgress?: boolean): Observable<HttpResponse<Pet>>;
        //public updatePet(body: Pet, observe?: 'events', reportProgress?: boolean): Observable<HttpEvent<Pet>>;
        public updatePet(body: Pet, observe: any = 'body', reportProgress: boolean = false ): Observable<any>