简体   繁体   中英

Inject a service in Angular

I'm currently working through a tutorial to learn angular. I've some problems a problem to reproduce and to understand the example on how to inject a service as dependency.

Angular version: 7.2.9

As more advanced debugging techniques were not yet covered I've tried to find the problem using console.log(...). I've added the following in my app.components constructor:

export class AppComponent {
  userLogin: UserLoginService;

  constructor() {
    console.log( this.userLogin );
    console.log( UserLoginService );
  }

This results in:

> undefined
> ƒ UserLoginService() {
        console.log('Hello world from the user login service.');
    }

The service is defined as

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

@Injectable({
  providedIn: 'root'
})
export class UserLoginService {
  constructor() {
    console.log( 'Hello world from the user login service.' );
  }
}

then I try to use it in app.components:

import { Component } from '@angular/core';
import { UserLoginService } from './user/user-login.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  userLogin: UserLoginService;

  constructor() {
    console.log( this.userLogin );
    console.log( UserLoginService );
  }
}

I do not understand why the member userLogin remains undefined . Any hint to pinpoint the problem would be much appreciated.

Please use as below

import { Component } from '@angular/core';
import { UserLoginService } from './user/user-login.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {

  constructor(private userLogin:UserLoginService) {
    console.log( this.userLogin );

  }
}

First you should put your service in providers then inject that service in constructor when you put your service in the providers then a new instance of the service will get created.

import { Component } from '@angular/core';
    import { UserLoginService } from './user/user-login.service';

    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.scss'],
      providers:[UserLoginService ]
    })
    export class AppComponent {


      constructor(private userLogin:UserLoginService ) {
        console.log( this.userLogin );

      }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM