Create an angular service with a typescript rest C

2019-08-15 10:22发布

问题:

I am using Angular 1.4.7 with typescript I have an autogenerated Client with Swagger in typescript to call a rest service like this:

module API.Client {
'use strict';

export class DefaultApi {
    ...

I am trying to use it by doing:

import TDRService = API.Client.DefaultApi;

export class ListaTrtController {
    private tdrservice: TDRService;

/* @ngInject */
constructor(service: TDRService) {
     this.tdrservice = service;
}

But I receive the error "Unknown provider: serviceProvider <- service <- ListaTrtController". How can I fix this problem?

回答1:

Register your service in angular with the name that you will use in the injections.

module API.Client {
'use strict';

export class DefaultApi {
    ...

angular.module('yourmodule').service('TDRService', DefaultApi);

Angular will use the variable name (Not the type), so it has to be the same name as it was registered in angular. And, you can use private in the constructor instead of doing the assignment like you did.

import TDRService = API.Client.TDRService;

export class ListaTrtController {

/* @ngInject */
constructor(private TDRService: TDRService) {
}