AppInjector get is deprecated, use Type<T> or InjectionToken<T>
Asked Answered
D

0

2

I am trying to get rid of this tslint warning:

WARNING: get is deprecated: from v4.0.0 use Type or InjectionToken

The way I have my code setup is like this:

app.injector.ts

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

export let AppInjector: Injector;

export function setAppInjector(injector: Injector) {
    if (AppInjector) {
        // Should not happen
        console.error('Error: AppInjector was already set');
    }
    else {
        AppInjector = injector;
    }
}

app.module.ts

...
import { setAppInjector } from './app-injector';
...

export class AppModule {
    constructor(private injector: Injector) {
        setAppInjector(injector);
    }
}

somecomponent.component.ts

...
import { Router } from '@angular/router';
import { AppInjector } from '../../app-injector';
...

export class SomeComponent {
    private router = AppInjector.get(Router);

    constructor() { /* code here */ }
}

I can't do private router: Router inside the constructor of somecomponent.component.ts, which is why I'm doing it like this (it is requirement, I can't change it).

So my main question is how can I change the line private router = AppInjector.get(Router) to get rid of the warning? Any help would be appreciated, thank you!

Deadfall answered 13/4, 2018 at 14:11 Comment(6)
@underscore_d "If I use a non-abstract class, the .get<T>(T) syntax works."Bounden
I tried AppInjecter.get<Router>(Router) and I got the same error.Deadfall
You shouldn't get it after that. The reason is because that error shows up because the get(...) version has the jsdoc comment that is causing you to see that: github.com/angular/angular/blob/…Bounden
Like mentionned, AppInjector.get<Router>(Router) should work Are you using ng serve or webpack's watch feature? If so, try stoppping and restarting the server. I had a similar problem yesterday with EventEmitter<T>. After getting the syntax wrong once, it only worked with correct syntax after restartBackup
Not sure what is wrong then. I restarted the server and and my IDE with the same warning. Maybe I'll just turn off the warning in tslint (not what I want to do though :( ).Deadfall
duplicate: #48661438Devoted

© 2022 - 2024 — McMap. All rights reserved.