【发布时间】:2021-01-23 10:44:30
【问题描述】:
- 自动注入
HttpClient到扩展类HttpHelper而不注入基类LoginService
我有许多具有 HTTP API 调用的服务。我创建了一个通用的 HTTP 类,它实例化 httpClient 和其他一些服务可以直接使用的辅助变量和函数,而无需重复实例化。
login.service.ts
@Injectable()
export class LoginService extends HttpHelper{
constructor(private http: HttpClient,
private authService: AuthService,
private userManagementService: UserManagementService) {
super(this.http);
}
login(data: IAuthPayload): Observable<any> {
return this.http.post(this.apiUrl + '/users/login', data, this.getHttpOptions({
auth: false
}))
.pipe(
map((res: ILoginResponse) => {
AuthService.setToken(res.data.token);
this.userManagementService.setUserData(res.data.user);
this.authService.setAuthState({ is_logged_in: true });
})
);
}
}
http.helper.ts
export class HttpHelper {
protected apiUrl = '';
constructor(private http: HttpClient) {
this.apiUrl = ENVIRONMENT.API_ENDPOINT;
}
protected getHttpOptions(options?: CustomHttpHeaderOptions) {
// function Definition
}
// Many More members here
}
-
LoginService扩展HttpHelper和httpClient实例化必须在HttpHelper中,而不是在任何服务中。例如LoginService。 - 如果我们只是扩展
HttpHelper而不将httpClient注入LoginService,这是否可能。httpClient应该自动注入httpHelper,我们将在LoginService中使用httpClient而不将其注入服务并直接使用httpHelperhttpClient实例。
【问题讨论】:
标签: angular dependency-injection