Value Provider: useValue

As we know that Angular provides different types of providers such as class provider, alias provider, value provider and factory provider. So in this article we will learn about Value provider step by step with example.

useValue is a value provider that returns a fixed value for dependency injection. Injector does not create the object in this case, but we create the object and that object is configured with the provider using useValue. It is used in the following way.

Find following the two fixed values.

const Angular_Book = new Book('Learn Angular', 'Version 7');
export const Angular_Message = new InjectionToken<string>('Learn Angular 6!'); 

Now they will be configured as follows.

providers: [ 
	    { provide: Book, useValue: Angular_Book },
		{ provide: Angular_Message, useValue: 'Learn Angular 7 step by step' }
	]

If Book has been injected into any component or service using the constructor, the injector will be injected there with the Angular_Book fixed value. In the same way, wherever Angular_Message is injected, they will receive Hello World! value. Now find the example.

Now we will create an example for Alias Provider: useExisting and Folder structure for this example as shown below.

src
├── app
│   ├── book.ts
│   ├── book.component.ts
│   ├── app.component.ts
│   ├── app.module.ts

book.ts

export class Book {
	constructor(public name: string, public version: string){}
}

book.component.ts

import { Component, OnInit, InjectionToken, Inject } from '@angular/core';
import { Book } from './book';

const Angular_Book = new Book('Learn Angular', 'Version 7');
export const Angular_Message = new InjectionToken<string>('Learn Angular 6!'); 

@Component({
    selector: 'book',
     providers: [ 
	    { provide: Book, useValue: Angular_Book },
		{ provide: Angular_Message, useValue: 'Learn Angular 7 step by step' }
	],     
    template: `
	     <p>Book Name: <b>{{book.bookname}}</b> </p>
		 <p>Version: <b>{{book.version}}</b></p>
		 <p>Message: <b>{{message}}</b> </p>
	`
})
export class BookComponent implements OnInit {
	constructor(private book: Book, 
	            @Inject(Angular_Message) private message: string) { }
	
	ngOnInit() {
	}
}

app.component.ts

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

@Component({
  selector: 'app-root',
  template: `
          <book></book>
  `
})
export class AppComponent {
}

app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppComponent }  from './app.component';
import { BookComponent }  from './book.component';

@NgModule({
  imports: [     
        BrowserModule
  ],
  declarations: [
        AppComponent,
		BookComponent,
  ],
  providers: [ 
  ],  
  bootstrap: [
        AppComponent
  ]
})
export class AppModule { }

when you run the application, you will get the output as shown below.

sahosoft-Tutorials-Class-Provider-useClass

download demo source code

Value Provider: useValue