首页 文章

在Angular2中使用生成的Swagger TypeScript Rest Client

提问于
浏览
5

我正在使用Angular 2和TypeScript处理Meteor Web应用程序 . 对于使用REST API,我使用Swagger Codegen生成了客户端代码 . 不幸的是GitHub上没有样本,如何使用其余的客户端 .

我有一个角度2视图组件,它注入一个Angular 2服务(ProductTreeService)和生成的API(都标记为“@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
    {
        //...
    }
}

虽然角度服务只是可访问的并且一切正常,但是当我注入UserApi时应用程序崩溃了 . UserApi和ProductTreeService之间的唯一区别是构造函数:服务没有构造函数参数,生成的Api class具有:

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

那么如何注入生成的API呢?

2 回答

  • 2

    经过进一步的研究,我得到了解决方案 . 其余客户端UserApi的构造函数正在等待HTTP提供程序,如下所示:

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

    来自Java,我想也许这个提供程序必须在注入此API的构造函数中以某种方式初始化 . 实际上,这个初始化必须在包含注入组件的NgModule中完成,如thread中所述 .

    这个解决方案对我有用 .

  • 0

    老问题,但......你应该怎么做:

    providers: [
    {
      provide: API_BASE_URL, // or BASE_PATH
      useFactory: () => { 
          return environment.apiBaseUrl // or return just "your base url as text"
      }
    }]
    

相关问题