【问题标题】:Providers and Modules childs提供者和模块的孩子
【发布时间】:2016-06-16 16:06:56
【问题描述】:

我不明白为什么我需要在父组件中设置提供程序,如果我稍后将它作为服务导入子组件中。

这是服务:

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

@Injectable()
export class AService {
 doSomething(){
    return 'i am a service';
 }
}

这是父母:

import { Component } from '@angular/core';
import { AService }  from './a-service';
import { ChildComponent }  from './child.component';

@Component({
  selector: 'my-parent',
  directives: [ChildComponent],
  providers:[AService],
  template:'<my-child></my-child>'
})

export class ParentComponent{ }

angular2 文档说:link here

仔细查看@Component 元数据的提供者部分。现在可以在此 HeroesComponent 及其所有子组件中注入一个 HeroService 实例。

但是,在子组件的定义中,无论如何我都需要导入服务。如果我不这样做,它会崩溃:

import { Component } from '@angular/core';
import { AService }  from './a-service';

@Component({
  selector: 'my-child',
  template:'<p> this is the {{service_returned_data}}'
})

export class ChildComponent{ 
  constructor(private _service: AService){}
  service_returned_data=_service.doSomething();
}

谁能解释一下这是什么意思?

【问题讨论】:

    标签: angular


    【解决方案1】:

    提供者和导入是两个完全不同的概念。

    • 提供者在注入器树中定义服务的实例范围(类似于组件和指令的结构)

    • 导入在整个应用程序中唯一标识类型,用于静态类型检查、自动完成和 Angulars DI 使用构造函数参数的类型信息作为键来查找提供程序以获取实例并传递它给构造函数。

    【讨论】:

    • 你是对的。 Angular 在下面几行回复我的问题:link.
    • 基本上这个意思是让服务成为单例
    猜你喜欢
    • 1970-01-01
    • 2021-03-10
    • 1970-01-01
    • 2018-07-24
    • 2023-02-05
    • 2021-10-29
    • 2018-05-04
    • 2017-07-24
    • 1970-01-01
    相关资源
    最近更新 更多