简体   繁体   English

依赖注入在 angular 应用程序中不起作用

[英]Dependency Injection not working in angular app

I am having trouble in accessing the properties of my service.我无法访问我的服务的属性。 As you can see in the pictures below, Decorators and imports are in order and the service itself was properly added and injected.如下图所示,装饰器和导入是有序的,并且服务本身已正确添加和注入。 I don't seem to understand what is causing the error, since the "normal procedure" of dependency injection is being respected.我似乎不明白是什么导致了错误,因为依赖注入的“正常程序”受到尊重。 The service in question is the Register service.有问题的服务是注册服务。 Any advices to resolve the problem?有什么建议可以解决这个问题吗? Thanks in advance.提前致谢。

app.module.ts app.module.ts

在此处输入图像描述

register.component.ts注册组件.ts

在此处输入图像描述

register.service.ts注册服务.ts

在此处输入图像描述

Part of the register.component.html部分寄存器.component.html

在此处输入图像描述

Errors I am getting(all similar):我得到的错误(都相似):

在此处输入图像描述 ** **

Files:文件:

在此处输入图像描述

I'm pointing 2 mistakes in the above code snippet.我在上面的代码片段中指出了 2 个错误。

  1. Yes Obviously while implementing OnInit life cycle hook in the RegisterService class.是的,显然在 RegisterService class 中实现OnInit生命周期挂钩时。 Since all life cycle hooks are for components not for services.因为所有生命周期钩子都是针对组件而不是服务。

  2. Since you already added below line in the RegisterService class.由于您已经在 RegisterService class 中添加了以下行。

@Injectable({ providedIn: 'root' }) @Injectable({ providedIn: 'root' })

You don't need to add this service class again in the provider array of app.module.ts class.无需在 app.module.ts class 的 provider 数组中再次添加此服务 class Since @Injectable({providedIn: 'root'}) already means you injected the service at root level.由于@Injectable({providedIn: 'root'})已经意味着您在根级别注入了服务。

services didn't support component lifecycle like OnInit etc服务不支持 OnInit 等组件生命周期

your service can be like this你的服务可以是这样的

@Injectable()
export class FormService {
  contactForm: FormGroup;

  constructor(private formBuilder: FormBuilder) {
    this.createContactForm();
  }

  createContactForm(){
    this.contactForm = this.formBuilder.group({
      fullName: [''],  
      email: [''],
      message: ['']
    });
  }
}

example 例子

Only Directive and component instances have a lifecycle so register.service.ts is created like component只有指令和组件实例具有生命周期,因此 register.service.ts 像组件一样创建

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

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