Skip to content

Function: useOptionalInjection()

ts
function useOptionalInjection<T, F>(
   host: ReactiveControllerHost & HTMLElement, 
   optionsOrInjectionId: 
  | UseOptionalInjectionOptions<T, F>
  | ServiceIdentifier<T>, 
onFallback?: OptionalInjectionFallback<F>): UseOptionalInjectionValue<T, F>;

Defined in: src/wirestate-lit/consumption/use-optional-injection.ts:89

Consumes a service if the nearest container has it.

Type Parameters

Type ParameterDefault typeDescription
T-The type of the value being resolved.
FnullThe type returned by the fallback function.

Parameters

ParameterTypeDescription
hostReactiveControllerHost & HTMLElementHost element.
optionsOrInjectionId| UseOptionalInjectionOptions<T, F> | ServiceIdentifier<T>Service token or options.
onFallback?OptionalInjectionFallback<F>Fallback for missing bindings.

Returns

UseOptionalInjectionValue<T, F>

Mutable injection holder.

Remarks

Missing token means fallback result, or null when no fallback exists.

Example

typescript
class MyElement extends LitElement {
  private logger = useOptionalInjection(this, FileLogger, (container) => container.get(ConsoleLoggerService));

  render() {
    return html`<div>${this.logger.value?.getName() ?? "No logger"}</div>`;
  }
}