michael
michael

Reputation: 4547

ionic2 how do you provide/@Inject an OpaqueToken?

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.

Upvotes: 0

Views: 199

Answers (1)

yurzui
yurzui

Reputation: 214085

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

Upvotes: 2

Related Questions