0

I have the following code to provide/inject an OpaqueToken, but I'm getting an error when I try to use it. VM4745:24 Error: (SystemJS) Can't resolve all parameters for HomePage: (NavController, ?).

app.module.ts

    import { NgModule, ErrorHandler, OpaqueToken } from '@angular/core';
    // ...

    export const DEBUG = new OpaqueToken("debug");
    export function provideDebug(window: Window){
        if (~window.location.search.toLocaleLowerCase().indexOf("debug=true")){
            return true;
        }
        return false;
    }

    @NgModule({
    // ...
    providers: [
        { provide: 'Window',  useValue: window }
        , { provide: DEBUG, useFactory: provideDebug, deps: [Window] }
    ]
    })

home.ts

    import { Component, Inject } from '@angular/core';
    import { DEBUG } from './app.module';
    // ...

    @Component({
        selector: 'page-home',
        templateUrl: 'home.html'
    })
    export class HomePage {
        constructor(
            @Inject(DEBUG) isDebug: boolean,
            @Inject(Window) window: Window
        ) {
            console.log("DEBUG=", isDebug);
        }
    }

Here's a plunkr: http://plnkr.co/edit/6N1FKQpS8vbKnwPKJQW1?debug=true&p=preview

solution Here's the solution for injecting an OpaqueToken (from a different file), and also injecting the window object, based on the answer below.

Plunker

Note: the plunker doesn't send the query string to the runtime correctly, but in practice this will not be an issue.

michael
  • 4,377
  • 8
  • 47
  • 73

1 Answers1

2

You have a circular dependency.

Move DEBUG and provideDebug to a separated file for example debug.ts The second error is here:

deps: [Window]

there is no Window provider in your configuration. Use deps: ['Window'] instead as you defined your provider as string

 providers: [
   { provide: 'Window',  useValue: window },
   { provide: DEBUG, useFactory: provideDebug, deps: ['Window'] }  
 ]

Updated Plunker

yurzui
  • 205,937
  • 32
  • 433
  • 399
  • `debug.ts` solves the problem, but I'm unclear why this is a circular dependency. can you explain? Also, I was trying to inject `Window` with this line: `{ provide: 'Window', useValue: window }` which seemed to give me access to `window.location`, but now it doesn't... It seems to work in your updated Plunker, but the href=`http://run.plnkr.co/vAabzuRXur4BTnVL/` – michael Feb 21 '17 at 19:32
  • `app.module.ts => homepage.ts => app.module.ts`. Try to put `console.log(DEBUG);` in homepage.ts and you will see that it is `undefined` – yurzui Feb 21 '17 at 19:38
  • got it. Next: how do I inject the JS window object? I thought that was the recipe... – michael Feb 21 '17 at 20:01
  • http://stackoverflow.com/questions/34177221/angular2-how-to-inject-window-into-an-angular2-service – yurzui Feb 21 '17 at 20:03
  • why doesn't this work? (it used to...) http://stackoverflow.com/questions/40222084/how-to-inject-window-into-angular-2-1-0 – michael Feb 21 '17 at 20:25