如何动态传递接口作为通用类型以函数调用
例如,我有此代码。 API可以返回4个不同接口的数据。如何动态传递接口函数调用?
// Service
getCandidateConnectedProfiles<T>(source: string, candidateId: string): Observable<T> {
return this.http
.get<ServerResponse<T>>(`${apis.getCandidateConnectedProfiles}/${source}/${candidateId}`)
.pipe(
map(response => response.result)
);
}
// Component
this.candidateProfileService.getCandidateConnectedProfiles(linkName.toLowerCase(), linkId)
.subscribe();
我试图在服务方法中添加通用,但是我不知道如何将接口从组件函数调用,从而从响应中获取该接口。因此,如果我的 linkName ==='一个''我想传递一个名为一个的接口,依此类推。
this.candidateProfileService.getCandidateConnectedProfiles<Here i want my interface depending on linkName>(linkName.toLowerCase(), linkId)
.subscribe();
For example i have this code. API can return data of 4 different Interfaces. How can i dynamically pass the interface to function call ?
// Service
getCandidateConnectedProfiles<T>(source: string, candidateId: string): Observable<T> {
return this.http
.get<ServerResponse<T>>(`${apis.getCandidateConnectedProfiles}/${source}/${candidateId}`)
.pipe(
map(response => response.result)
);
}
// Component
this.candidateProfileService.getCandidateConnectedProfiles(linkName.toLowerCase(), linkId)
.subscribe();
I was trying to add a generic to the service method, but i can't figure out how to pass interface to function call from component, to get that interface from the response. So if my linkName === 'one' i want to pass an interface named One and so on.
this.candidateProfileService.getCandidateConnectedProfiles<Here i want my interface depending on linkName>(linkName.toLowerCase(), linkId)
.subscribe();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不相信您可以做到这一点,但是您可以像这样这样做类型:
这样,您要确保无论您将哪种对象投入通用的对象,都必须是实现界面的某些东西。像这样使用:
I don't believe you can do that, but you can give a type to T like so:
This way you make sure that no matter what object you throw into the generic it has to be something that implements said interface. Use it like so: