Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
756 views
in Technique[技术] by (71.8m points)

angular - What are providers in Angular2?

In the Angular2 component configuration providers is one of the keys that we could specify. How are these providers defined and what are they used for?

@Component({
  ..
  providers: [..],
  ..
})

Note:

Angular2 documentation is gradually maturing but still sparse. It currently defines providers as:

An array of dependency injection providers for services that the component requires.

This recursive definition isn't very helpful. A more detailed explanation with an example would really help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Providers are usually singleton (one instance) objects, that other objects have access to through dependency injection (DI).

If you plan to use an object multiple times, for example Http service in different components, you can ask for same instance of that service (reuse it). You do that with the help of DI by providing a reference to the same object that DI creates for you.

@Component){
  ..
  providers: [Http]
}

..instead of creating new object every time:

@Component){}
class Cmp {
  constructor() {
    // this is pseudo code, doens't work
    this.http = new Http(...options);
  }
}

This is an approximation, but that's the general idea behind Dependency Injection - let the framework handle creation and maintenance of reusable objects... Provider is Angular's term for these reusable objects (dependencies).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...