简体   繁体   English

在Angular中注入服务

[英]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 角版本:7.2.9

As more advanced debugging techniques were not yet covered I've tried to find the problem using console.log(...). 由于尚未涵盖更高级的调试技术,因此我尝试使用console.log(...)查找问题。 I've added the following in my app.components constructor: 我在app.components构造函数中添加了以下内容:

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: 然后我尝试在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 . 我不明白为什么成员userLogin仍未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 );

      }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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