简体   繁体   English

Angular Library使用时未运行ngOnInit

[英]Angular Library is not running ngOnInit when used

I'm following the Angular CLI 6 instructions for creating a library here . 我正在按照Angular CLI 6的说明在此处创建库。 I was able to make my library, and build it successfully. 我能够制作我的库并成功构建它。 The library consists of a Component I am using for the UI and has an HTML selector . 该库由我用于UI的Component组成,并具有HTML selector

@Component({
  selector: 'my-lib',
  templateUrl: './my-lib.component.html',
  styleUrls: ['./my-lib.component.css'],
  providers: [MyService],
})

export class MyComponent implements OnInit {
  @Input() id: string;

  constructor(
    private myService: MyService) {
    console.log("constructor");    
  }

  ngOnInit {
    console.log("ngOnInit");
    this.myService.DoStuff();
  }
}

Now I have a separate project I am trying to use this library in. I'm not publishing it yet, so I am using it by copying the contents of dist/<my-lib> into the node_modules of the other project. 现在,我有一个单独的项目正在尝试使用该库。我尚未发布它,因此我将dist/<my-lib>的内容复制到另一个项目的node_modules来使用它。 I was using npm link before, but I hit the issue described here , and this solution worked for me. 我以前使用过npm link ,但是遇到了此处描述的问题,该解决方案对我来说很有效。

I can successfully import the library and Module and use the Component in the HTML file with its selector, along with passing inputs: <my-lib [id]="'my-id'"> . 我可以成功导入库和Module并在HTML文件中使用带有其选择器的Component以及传递的输入: <my-lib [id]="'my-id'"> The id is passed down correctly, but the logic in the ngOnInit that is not getting run. id已正确传递,但ngOnInit中的逻辑未运行。 The console does NOT print "ngOnInit" . 控制台不会打印"ngOnInit" But it DOES print "constructor" , and the Component UI elements show up correctly. 但是,它确实打印出"constructor" ,并且Component UI元素正确显示。

Am I missing something to get the ngOnInit logic to run? 我是否缺少一些让ngOnInit逻辑运行的东西?

EDIT: I should mention that the library is running: 编辑:我应该提到该库正在运行:

  • "@angular/core": "^6.0.3"

  • "@angular/cli": "~6.0.7"

and the project I'm trying to use the library in is: 我试图在其中使用该库的项目是:

  • "@angular/core": "^5.0.1"
  • "@angular/cli": "^1.6.5"

Not sure if this will affect anything or not. 不知道这是否会影响任何事情。

EDIT2: Fix example code. EDIT2:修复示例代码。

Only issue i see is that your instance of the service also has the same name, change it as 我看到的唯一问题是您的服务实例也具有相同的名称,请将其更改为

constructor(
    private apiService: myService) {
    console.log("constructor");    
  }

ngOnInit {
    console.log("ngOnInit");
    this.apiService.DoStuff();
  }

also hope that you have imported, 也希望您已经导入

import { Component, OnInit } from '@angular/core';

also remove providers in component and move it to the module level. 还删除组件中的提供程序并将其移至模块级别。

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

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