Monday, December 31, 2018

Difference between providers and viewproviders

Service declared by providers are accesbile by content children also but service declared by viewproviders are not accesbile by content children, it accesbile by component and and its view children.


Lets peek at the declaration of the TodoAppComponent:

class TodoList {
  private todos: Todo[] = [];
  add(todo: Todo) {}
  remove(todo: Todo) {}
  set(todo: Todo, index: number) {}
  get(index: number) {}
  getAll() {}
}
@Component({
  // ...
  viewProviders: [TodoList]
  // ...
})
class TodoAppComponent {
  constructor(private todos: TodoList) {}
  // ...
}

Inside of the @Component decorator we set the viewProviders property to an array with a single element - the TodoList class. The TodoList class holds all the todo items, which are entered in the current session.

We inject the TodoList service in the TodoAppComponent’s constructor, but we can also inject it in any other directive’s (or component) constructor, which is used in the TodoAppComponent’s view. This means that TodoList is accessible from:

TodoList
TodoComponent
TodoInputComponent

However, if we try to inject this service in FooterComponent’s constructor we are going to get the following runtime error:

ORIGINAL EXCEPTION: No provider for TodoList!
This means that providers declared in given component with viewProviders are accessible by the component itself and all of its view children.

In case we want to make the service available to FooterComponent as well we need to change the declaration of the component’s providers from viewProviders to providers.

When to use viewProviders?
Why would I use viewProviders, if such providers are not accessible by the content children of the component? Suppose you’re developing a third-part library, which internally uses some services. These services are part of the private API of the library and you don’t want to expose them to the users. If such private dependencies are registered with providers and the user passes content children to any of the components exported by the public API of your library, she will get access to them. However, if you use viewProviders, the providers will not be accessible from the outside.

https://medium.com/@tkssharma/understanding-viewchildren-viewchild-contentchildren-and-contentchild-b16c9e0358e

No comments:

Followers

Link