【发布时间】:2019-03-07 12:27:28
【问题描述】:
我正在为我的前端构建一堆有角度的 REST 服务。在那里,我认为拥有一个母类 BaseRestService 是一个好主意,它实现了所有相同的东西,比如标题和一些辅助函数。
但是当我的子服务扩展BaseRestService 时,当我调用一些子函数时,我得到TypeErrors。我尝试调试,可以看到子服务不是SomeExampleChildSerivce 类型,而是BaseRestService 类型。有人可以解释这种行为或告诉我我做错了什么吗?
您可以在下面看到我的BaseRestService 和ChildService 的代码:
BaseRestService:
@Injectable({
providedIn: 'root'
})
export abstract class BaseRestService {
headers = new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': `JWT ${this.authService.getToken()}`
});
constructor(
public httpClient: HttpClient,
public logger: LoggingService,
public authService: AuthenticationService,
) { }
public refreshToken(): void {
this.headers = new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': `${this.authService.getToken()}`
});
}
}
儿童服务:
@Injectable({
providedIn: 'root'
})
export class DimensionService extends BaseRestService{
private url: string = `${BASE_URL}/dimensions`;
constructor(
public httpClient: HttpClient,
public logger: LoggingService,
public authService: AuthenticationService,
){
super(httpClient, logger, authService);
}
get(url: string): Observable<DimensionAttribute> {
return this.httpClient.get<DimensionAttribute>(url, { headers: this.headers })
}
list(url?: string, page = 0, size = 20): Observable<Page<DimensionAttributeWrapper>> {
if (!url) url = `${this.url}?page=${page}&size=${size}`;
return this.httpClient.get<Page<DimensionAttributeWrapper>>(url, { headers: this.headers })
}
}
【问题讨论】:
-
我不知道为什么,但你可以简单地将
BaseRestService注入到DimensionService的构造函数中 -
好的,但我很想知道为什么扩展不起作用。
-
你到底得到了什么错误?哪一行给你这样的错误?
-
错误发生在我使用子服务的组件中。我现在有一个解决方法,所以不能告诉你确切的错误信息,但它就像
TypeError: CildService <some function> is not a function。无论哪个子服务,子服务器的每个功能都会出现相同的错误。我无法调用子函数的任何函数,只能调用可调用的父函数。 -
我已经像其他所有服务一样注入了该服务,作为组件构造函数中的参数。
标签: angular typescript angular6 extends