简体   繁体   English

如何在提供者内部使用提供者

[英]How to use a Provider inside of provider

I am using ionic2, which is Angular2, but this question is more Angular2 than Ionic framework.我使用的是 ionic2,也就是 Angular2,但是这个问题比 Ionic 框架更像是 Angular2。 I have a provider such as this:我有一个像这样的提供者:

import {Injectable, Provider, Inject} from '@angular/core';
import {Http, Response, Headers} from '@angular/http';

@Injectable()
export class MyFirstProvider{

  constructor( @Inject(Http) http) {
      this.http = http;
  }
.
.
.

I have another provider such as this:我有另一个供应商,例如:

import {Injectable, Provider, Inject} from '@angular/core';
import {Http, Response, Headers} from '@angular/http';

@Injectable()
export class MySecondProvider{

  constructor( @Inject(Http) http) {
      this.http = http;
  }

  myCoolFunction(){
    console.log('I am one cool function'); 
  }
.
.
.

How can I use MySecondProvider's myCoolFunctions inside of MyFirstProvider?如何在 MyFirstProvider 中使用 MySecondProvider 的 myCoolFunctions?

By injecting it通过注入

@Injectable()
export class MyFirstProvider{

  constructor(private http:Http, 
      private mySecond: MySecondProvider) {}

  someMethod(){
    this.mySecond.myCoolFunctions();
  }
}

These classes are services, not providers.这些类是服务,而不是提供者。 These services can and need to be registered as providers.这些服务可以并且需要注册为提供者。 A provider is a combination of key and value construction instruction.提供者是键和值构造指令的组合。 When DI looks up a type (key) it searches a components injector and its parent injectors until it finds one with a matching key and then returns its instance (the service).当 DI 查找类型(键)时,它会搜索组件注入器及其父注入器,直到找到具有匹配键的注入器,然后返回其实例(服务)。

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

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