代码之家  ›  专栏  ›  技术社区  ›  Amey

Angular 5中构造函数参数与new关键字的初始化?

  •  -1
  • Amey  · 技术社区  · 8 年前

     import { Component,OnInit } from '@angular/core';
        import {exampleClass} from './exampleClass'
        @Component({
          selector: 'app-root',
          templateUrl: './app.component.html',
          styleUrls: ['./app.component.css']
        })
        export class AppComponent {
           list: number[] = [1, 2, 3];
    
           constructor(a:exampleClass) {
            a.hello();
           }
        }
    

    代码2:

    import { Component,OnInit } from '@angular/core';
    import {exampleClass} from './exampleClass'
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent {
       list: number[] = [1, 2, 3];
    
       constructor() {
         const a = new exampleClass ;
    
       }
    
    }
    

    示例类。ts Cose:

    export class exampleClass {
        hello(){
            console.log("A");
        }
    }
    

    为什么代码1给出错误,代码在控制台中打印A,这两种初始化方法有什么区别?

    3 回复  |  直到 8 年前
        1
  •  1
  •   Sravan    8 年前

    在您的第一个代码中,

    export class AppComponent {
        list: number[] = [1, 2, 3];
        constructor(a:exampleClass) {
          a.hello();
        }
     }
    

    这个 exampleClass 应该是 service services 可以注入 constructor 作为一个 parameter .

    因此,您可能会得到错误 HeroDetailComponent没有提供程序

    所以,如果 示例类 是一项服务,它可能会起作用。

        2
  •  1
  •   Oscar Paz    8 年前

    您可能想了解 依赖项注入 角度: https://angular.io/guide/dependency-injection-pattern (也可能是一般情况下)。

    在第一种情况下, AppComponent 不需要知道任何关于 exampleClass . 在第二种情况下,您要决定使用的是什么类。

    在第一种情况下 AppComponent应用程序组件 AppComponent应用程序组件 与紧密耦合 示例类 .

    在第一种情况下,您可以决定组件将接收何种类型的实例,而不会影响组件。在第二种情况下,情况并非如此。如果你想通过,不要 示例类 ,但作为派生类,您应该接触它。事实上,如果这些类的构造函数不是无参数的, AppComponent应用程序组件 也应该知道如何实例化它们。

    我想,你收到错误的原因是你没有装饰 示例类 具有 @Injectable() . 这个decorator告诉Angular,这个类可以通过依赖注入进行实例化。

    此外,您应该添加 示例类 providers 您的 AppModule

    @Injectable() export class exampleClass { ... }
    
    @NgModule({
        providers: [exampleClass],
        ...
    })
    export class AppModule { }
    
        3
  •  1
  •   The Segfault    8 年前

    代码1是您希望服务 组件之间共享 .

    代码为1的所有其他组件将能够

    console.log(this.service.data); // print 'test'
    

    代码2实例化它,使服务 一个新实例作用域为您的组件 .

    推荐文章