injectContext
injectContext<T>(el: Element, key: ContextKey<T>): { promise: Promise<T>; cancel: () => void }Asks the nearest provider for a value, once.
Usage
const { promise, cancel } = injectContext(el, Key);Return value
promise— resolves with the nearest provided value.cancel— withdraws the request.
It never settles when nothing provides
A missing provider means "not yet", not "no". The request stays pending, and it resolves when a provider appears and replays it — which is what makes mount order irrelevant.
If you need an answer now, or none, use injectContextSync().
From a component
$inject() is the same call with the element filled in, and it returns the promise directly:
class Output extends Base {
static config = { name: 'Output' };
async mounted() {
const count = await this.$inject(CountContext);
return count.subscribe((value) => {
this.$el.textContent = String(value);
});
}
}The pending request is unmount-scoped
$unmount() cancels it, and a new mount runs mounted() again and asks again. That is why mounted() is the right place: a component that outlives several cycles asks once per cycle, and never holds a request for a scope it has left.
The @inject field decorator asks once, at construction, instead.
It is one-shot
injectContext() and $inject() resolve with the first answer and stop. To follow providers as they come and go, use subscribeContext().