Exposing our new service to other components
With the authentication service provider now available from our application injector, we can begin hooking it up in other components: the login feature is the most logical starting point. First, open the LoginComponent
code unit and import the new AuthenticationService
token so that we can properly use its type to inject it into the component:
app/login/login.component.ts
import { Component } from '@angular/core';
import {
FormBuilder,
ControlGroup,
Validators,
Control } from '@angular/common';
import { Router } from '@angular/router-deprecated';
import { AuthenticationService } from '../shared/shared';
...
In the same code unit, let’s now update the constructor payload with a new argument annotated with the AuthenticationService
token, so the Angular 2 DI machinery becomes aware that this module requires that type to be injected:
constructor(
formBuilder: FormBuilder,
private router: Router,
private authService: AuthService) {
// Rest of constructor implementation remains unchanged
...
}
With all the code in place, now we can replace our authenticate()
method to remove the business logic:
authenticate() { let credentials: any = this.loginForm.value; this.notValidCredentials = !this.loginForm.valid && this.loginForm.dirty; this.authenticationService.login(credentials).then(success => { if (success) { this.router.navigateByUrl('/'); } else { this.notValidCredentials = true; } }); }