Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using generated Swagger TypeScript Rest Client in Angular2

I am working on a Meteor web application using Angular 2 and TypeScript. For using a REST API, I have generated client code with Swagger Codegen. Unfortunately there is no sample on GitHub, how to use the rest client.

I have an angular 2 view component which is injecting an Angular 2 service (ProductTreeService) and the generated API (both marked as "@Injectable"):

@Component({
    selector: 'panel-product-selection',
    template,
    providers: [ProductTreeService, UserApi],
    directives: [ProductTreeComponent]
})

export class PanelProductSelectionComponent
{
    private categoriesProductsTree: Collections.LinkedList<CategoryTreeElement>;
    private productTreeService: ProductTreeService;
    private userApi: UserApi;

    constructor(productTreeService: ProductTreeService, userApi: UserApi)
    {
        this.productTreeService = productTreeService;
        this.userApi = userApi;
    }

    ngOnInit(): void
    {
        //...
    }
}

While the angular service only is accessable and all is working fine, the application is crashing when I inject UserApi. The only difference between UserApi and ProductTreeService is the constructor: The service has no constructor parameters, the generated Api class has:

constructor(protected http: Http, @Optional()@Inject(BASE_PATH) basePath: string) {
    if (basePath) {
        this.basePath = basePath;
    }
}

So how can I inject the generated API?

like image 357
Dolf Avatar asked Oct 18 '22 02:10

Dolf


2 Answers

After further researches I got the solution. The constructor of the rest client UserApi is expecting an HTTP provider as following:

constructor(protected http: Http, @Optional()@Inject(BASE_PATH) basePath: string) {
    if (basePath) {
        this.basePath = basePath;
    }
}

Coming from Java, I thought maybe this provider has to be initialized somehow in the constructor which is injecting this API. In actual fact, this initialization has to be done in the NgModule containing the injecting component, as described in this thread.

This solution worked for me.

like image 101
Dolf Avatar answered Oct 29 '22 16:10

Dolf


I would use the environment.ts file with a property for the url:

export const environment = {
  production: false,
  basePath: 'https://virtserver.swaggerhub.com/user/project/1.0.0'
};

And then in the app.module you provide the config to the service:

  providers: [
    { provide: BASE_PATH, useValue: environment.basePath },
  ],

This works with Swagger generated code.

Hope that helps! (updated to Angular6+)

https://blog.angulartraining.com/how-to-manage-different-environments-with-angular-cli-883c26e99d15

like image 24
Dani P. Avatar answered Oct 29 '22 15:10

Dani P.