Adrien Castagliola
Adrien Castagliola

Reputation: 921

Call a service from @ngModule

I want to call a service imported in my @ngModule from a login component. This what i did but it's not working. I have just started to work on the A2 final version.

export class Login implements OnInit{
  constructor(
    private _service: Service
    ) {
  }
  ngOnInit() {
    this._service.login(value)
        .subscribe(x => console.log(x));
    }
  }
}

My @ngModule

import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { LoginService } from '../service/login.service'; 

import { Login } from './login.component';

export const routes = [
  { path: '', component: Login, pathMatch: 'full' }
];

@NgModule({
  declarations: [
    Login
  ],
  imports: [
    CommonModule,
    RouterModule.forChild(routes)
  ],
  providers: [LoginService]
})
export default class LoginModule {
  static routes = routes;
}

Any ideas ?

Upvotes: 0

Views: 1222

Answers (3)

Igor Janković
Igor Janković

Reputation: 5532

You have to import LoginService in Login component also and add it to constructor as:

constructor( _service: LoginService) {  }

Upvotes: 0

ranakrunal9
ranakrunal9

Reputation: 13558

Chage your component class to use LoginService

export class Login implements OnInit{
  constructor(
    private _service: LoginService
    ) {
  }
  ngOnInit() {
    this._service.login(value)
        .subscribe(x => console.log(x));
    }
  }
}

Upvotes: 1

Pankaj Parkar
Pankaj Parkar

Reputation: 136154

Inside constructor Service should be LoginService, as you wanted to access/create an instance of LoginService. Also make sure LoginService has been imported.

constructor(
   private _service: LoginService //<-- changed dependency type name
   ) {
}

Upvotes: 1

Related Questions