Inject service in a simple class constructor with Angular2

Discussão em 'Angular' iniciado por Greg, Setembro 17, 2025.

  1. Greg

    Greg Guest

    I created a Message class like this

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

    import { ApiService } from '../api.service';

    export class Message {
    timestamp: number;
    message: any;
    api: ApiService;

    constructor(message: any) {
    let injector = ReflectiveInjector.resolveAndCreate([ApiService]);
    this.api = injector.get(ApiService);
    this.timestamp = message.timestamp;
    this.message = message.message;
    }
    }


    I'm not injecting ApiService directly in the constructor parameters because I'm trying to avoid this: let nm = new Message(message, this.api)
    I don't want the service to be in the parameters.

    So I'm using the ReflectiveInjector but this code doesn't even work. I get this error : EXCEPTION: Error: Uncaught (in promise): No provider for Http! (ApiService -> Http) even if I include HTTP_PROVIDERS this way

    import { bootstrap } from '@angular/platform-browser-dynamic';
    import { enableProdMode } from '@angular/core';
    import { HTTP_PROVIDERS } from '@angular/http';

    import { AppComponent, environment } from './app/';
    import { appRouterProviders } from './app/app.routes';

    if (environment.production) {
    enableProdMode();
    }

    bootstrap(AppComponent, [
    appRouterProviders,
    HTTP_PROVIDERS,
    ])
    .catch(err => console.log(err));


    How can I use the constructor to instantiate my class and inject my services like this :
    let nm = new Message(message);

    Continue reading...

Compartilhe esta Página