angular - Angular10:扩展组件的自动注入依赖
问题描述
- 自动注入
HttpClient
扩展类HttpHelper
而不注入基类LoginService
我有很多服务都有 HTTP API 调用。我创建了一个通用 HTTP 类,它实例化 httpClient 和其他一些服务可以直接使用的辅助变量和函数,而无需重复实例化。
登录服务.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
我们将httpClient
在LoginService
不注入服务的情况下直接使用httpHelper
httpClient
实例。
解决方案
您可以使用 Angular Injector 轻松创建可注入类:
import {Injector} from '@angular/core';
/**
* Allows for retrieving singletons using `AppInjector.get(MyService)` (whereas
* `ReflectiveInjector.resolveAndCreate(MyService)` would create a new instance
* of the service).
*/
export let AppInjector: Injector;
/**
* Helper to set the exported {@link AppInjector}, needed as ES6 modules export
* immutable bindings (see http://2ality.com/2015/07/es6-module-exports.html) for
* which trying to make changes after using `import {AppInjector}` would throw:
* "TS2539: Cannot assign to 'AppInjector' because it is not a variable".
*/
export function setAppInjector(injector: Injector) {
if (AppInjector) {
// Should not happen
console.error('Programming error: AppInjector was already set');
}
else {
AppInjector = injector;
}
}
并以这种方式使用它:
import {AppInjector} from './app-injector';
const myService = AppInjector.get(MyService);
看到这个答案
推荐阅读
- python - 以数组和整数作为参数并返回一个数组
- java - 如何在 Tinkerpop (OrientDB) gremlin 查询中删除子图?
- c++ - || 的无关可见过载 防止|| 从要求子句中的短路
- java - 有没有办法缓存来自 firebase 数据库的信息以便快速工作?
- javascript - 如何从浏览器中读取 .AppImage
- azure - 在 Durable Functions 中处理服务总线消息
- mongodb - Mongo DB 副本磁盘写入
- node.js - Postman Form-Data 和 x-www-form-encoded 返回空数据
- node.js - Google Adminsdk 目录 API 访问权限
- mysql - MySQL GREATEST() 在 ORDER BY 子句中不起作用