Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
728 views
in Technique[技术] by (71.8m points)

angular - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...