Can't Inject service in angular 2 module with ASP Core 1.1 #634

Closed
opened 2025-08-09 17:17:03 +00:00 by fergalmoran · 0 comments
Owner

Originally created by @ahmagdy on 6/25/2017

Hi
i'm using generator-aspnetcore-spa and i'm trying to inject service into my app in Angular 2

@Injectable()
export class CommService {

  constructor(private http: Http) { }


  getUserIP() {
    return this.http.get('http://api.ipify.org/?format=json')
      .map(x => x.json());
  }

}

and add it to my component

@Component({
    selector: 'home',
    templateUrl: './home.component.html'
})
export class HomeComponent  {
    constructor(private service: CommService) { }
}

so i added providers: [ CommService] in sharedConfig "app.module.shared.ts"
when i'm trying to run the app i got

export const sharedConfig: NgModule = {
    bootstrap: [ AppComponent ],
    declarations: [
        AppComponent,
        NavMenuComponent,
        CounterComponent,
        FetchDataComponent,
        HomeComponent,
        LoginComponent
    ],
    imports: [
        RouterModule.forRoot([
            { path: '', redirectTo: 'home', pathMatch: 'full' },
            { path: 'home', component: HomeComponent },
            { path: 'counter', component: CounterComponent },
            { path: 'fetch-data', component: FetchDataComponent },
            { path: 'login', component: LoginComponent },
            { path: '**', redirectTo: 'home' }
        ])
    ],
    providers: [CommService]
};

Exception: Call to Node module failed with error: Error: Uncaught (in promise): Error: No provider for CommService!
Error: No provider for CommService!

i tried to add the service in providers in boot-server.ts

enableProdMode();

export default createServerRenderer(params => {
    const providers = [
        { provide: INITIAL_CONFIG, useValue: { document: '<app></app>', url: params.url } },
        { provide: 'ORIGIN_URL', useValue: params.origin },
        CommService
    ];

    return platformDynamicServer(providers).bootstrapModule(AppModule).then(moduleRef => {
        const appRef = moduleRef.injector.get(ApplicationRef);
        const state = moduleRef.injector.get(PlatformState);
        const zone = moduleRef.injector.get(NgZone);

        return new Promise<RenderResult>((resolve, reject) => {
            zone.onError.subscribe(errorInfo => reject(errorInfo));
            appRef.isStable.first(isStable => isStable).subscribe(() => {
                // Because 'onStable' fires before 'onError', we have to delay slightly before
                // completing the request in case there's an error to report
                setImmediate(() => {
                    resolve({
                        html: state.renderToString()
                    });
                    moduleRef.destroy();
                });
            });
        });
    });
});

and that's what i got

Exception: Call to Node module failed with error: Error: Uncaught (in promise): Error: No provider for Http! (CommService -> Http)
Error: No provider for Http! (CommService -> Http)
at Error (native)

So where i can import and inject my Services

*Originally created by @ahmagdy on 6/25/2017* Hi i'm using generator-aspnetcore-spa and i'm trying to inject service into my app in Angular 2 ``` @Injectable() export class CommService { constructor(private http: Http) { } getUserIP() { return this.http.get('http://api.ipify.org/?format=json') .map(x => x.json()); } } ``` and add it to my component ``` @Component({ selector: 'home', templateUrl: './home.component.html' }) export class HomeComponent { constructor(private service: CommService) { } } ``` so i added `providers: [ CommService]` in sharedConfig "app.module.shared.ts" when i'm trying to run the app i got ``` export const sharedConfig: NgModule = { bootstrap: [ AppComponent ], declarations: [ AppComponent, NavMenuComponent, CounterComponent, FetchDataComponent, HomeComponent, LoginComponent ], imports: [ RouterModule.forRoot([ { path: '', redirectTo: 'home', pathMatch: 'full' }, { path: 'home', component: HomeComponent }, { path: 'counter', component: CounterComponent }, { path: 'fetch-data', component: FetchDataComponent }, { path: 'login', component: LoginComponent }, { path: '**', redirectTo: 'home' } ]) ], providers: [CommService] }; ``` > Exception: Call to Node module failed with error: Error: Uncaught (in promise): Error: No provider for CommService! > Error: No provider for CommService! i tried to add the service in providers in boot-server.ts ``` enableProdMode(); export default createServerRenderer(params => { const providers = [ { provide: INITIAL_CONFIG, useValue: { document: '<app></app>', url: params.url } }, { provide: 'ORIGIN_URL', useValue: params.origin }, CommService ]; return platformDynamicServer(providers).bootstrapModule(AppModule).then(moduleRef => { const appRef = moduleRef.injector.get(ApplicationRef); const state = moduleRef.injector.get(PlatformState); const zone = moduleRef.injector.get(NgZone); return new Promise<RenderResult>((resolve, reject) => { zone.onError.subscribe(errorInfo => reject(errorInfo)); appRef.isStable.first(isStable => isStable).subscribe(() => { // Because 'onStable' fires before 'onError', we have to delay slightly before // completing the request in case there's an error to report setImmediate(() => { resolve({ html: state.renderToString() }); moduleRef.destroy(); }); }); }); }); }); ``` and that's what i got > Exception: Call to Node module failed with error: Error: Uncaught (in promise): Error: No provider for Http! (CommService -> Http) > Error: No provider for Http! (CommService -> Http) > at Error (native) So where i can import and inject my Services
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: github/JavaScriptServices#634
No description provided.