首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Angular10:扩展组件的AutoInject依赖性

Angular10:扩展组件的AutoInject依赖性
EN

Stack Overflow用户
提问于 2021-01-23 10:44:30
回答 1查看 53关注 0票数 0
  • Auto将 HttpClient 注入到扩展类 HttpHelper 而无需在基类 LoginService

中注入

我有许多具有HTTP调用的服务。我已经创建了一个公共httpClient,它实例化了httpClient和其他一些助手变量和函数,服务可以直接使用这些变量和函数,而无需重复实例化。

login.service.ts

代码语言:javascript
复制
@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

代码语言:javascript
复制
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扩展了HttpHelperhttpClient实例化,必须在HttpHelper中而不是在任何服务中。例如,如果我们只是扩展LoginService.
  • is,而不是将httpClient注入到LoginService中,这是可能的。httpClient应该自动注入httpHelper,我们将在LoginService中使用httpClient而不将其注入服务,并直接使用httpHelper httpClient实例。
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-01-23 12:44:19

您可以轻松地使用角喷射器创建您的可注射类:

代码语言:javascript
复制
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;
    }
}

并以这种方式使用:

代码语言:javascript
复制
import {AppInjector} from './app-injector';
const myService = AppInjector.get(MyService);

请参阅this answer

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65858265

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档