首页 > 解决方案 > Angular useValue and injection token

问题描述

In my angular app I have

{ provide: QUEUE, useValue: window.events }

in my providers. I was wondering how can I set QUEUE to use an empty array [] if window.events are undefined. I tried something like this and it didn't work.

  { provide: QUEUE, useValue: window.events || [] }

Here is what I have in QUEUE.injection-token.ts

import { InjectionToken } from '@angular/core';

export const \QUEUE = new InjectionToken<Array<AppEvent>>('QUEUE');

Thanks!

标签: angulardependency-injection

解决方案


window.events || [] check should be performed at runtime because window doesn't exist at compilation time.

It likely should be:

export function queueFactory(): any[] {
    return window.events || [];
}

...
providers: [ provide: QUEUE, useFactory: queueFactory }]
...

推荐阅读