简体   繁体   中英

Can I get metadata of generic type in typescript?

I have a decorated model class:

@Api('payments/deposit')
export class DepositsModel {
  public id: number;
  public created_at: Date;
  ...

In angular component constructor I'm injecting data service pointing to use my model class:

...
public constructor( 
  private $api: GridApiService<DepositsModel>
...
) {
  this.service = new GridService($api);
  ...
}
...

So, my cool component has a cool service, witch knows the type of data it work with...

Should know..

But how I can to get my model's metadata in my GridApiService? I've tried:

@Injectable()
export class GridApiService<T>{
  constructor(
    $http: HttpClient,
  ) {
    let api = Reflect.getMetadata('Api', T);
  }

And got Error message: 'T' only refers to a type, but is being used as a value here.

UPDATE

Can you advice me another way to pass initialization data to my GridApiService, witch should be injected through DI, not created with new keyword?

TypeScript types don't exist at runtime, with the exception of those that can be emitted as metadata via class decorators. Generic types cannot be emitted and don't exist for Angular DI. GridApiService<DepositsModel> doesn't matter for anything but type checking.

The connection between GridApiService and a DepositsModel should be expressed with class design, for example inheritance:

class DepositsGridApiService extends GridApiService {
  Model = DepositsModel;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM