Angular: Avoid forwardRef

ID

javascript.angular_avoid_forward_refs

Severity

low

Remediation Complexity

medium

Remediation Risk

low

Remediation Effort

medium

Resource

Code Smell

Language

JavaScript

Tags

angular, code-smell

Description

Reports calls to forwardRef(() ⇒ X). Angular’s forwardRef is a workaround for circular declarations between modules, providers and components — the dependency graph at injection time refers to a class that is declared later in source order. Most occurrences indicate the offending pair could be reordered, extracted into a separate file, or decomposed into smaller pieces that do not need a forward reference.

Rationale

// Bad — circular reference papered over with forwardRef.
const provider = {
  useExisting: forwardRef(() => HostService),
};

Forward references add a runtime indirection and obscure the dependency graph. Tools (DI tracing, IDE refactors, dead-code analysis) work better when every reference points at an already-declared class.

Remediation

Either reorder the declarations so the referent comes first, or pull the cycle apart by extracting a shared interface / token:

// Good — declare once, reference directly.
class HostService { ... }
const provider = { useExisting: HostService };

// Good — break the cycle with an injection token.
const HOST_TOKEN = new InjectionToken<HostService>("HostService");
@Injectable() class HostService implements HostContract { ... }