I have two components.LoginComponent and LandingComponent.I have to route from login page to landingpage after validating username and password. But I can't access router inside the service which was a global/page variable. It shows an error "TypeError: Cannot read property 'router' ".
import {Component} from 'angular2/core';
import { RouteConfig, ROUTER_DIRECTIVES, ROUTER_PROVIDERS, Router } from 'angular2/router';
import {LoginService} from './login.service';
import {NgForm} from 'angular2/common';
@Component({
selector: 'login',
templateUrl: './app/app-components/login/login.html',
styleUrls:['./app/app-components/login/login.css'],
directives: [ROUTER_DIRECTIVES],
providers:[LoginService]
})
export class LoginComponent {
//DECLARATIONS
login={username:"",password:""} ;
active = true;
submitted = false;
router:Router;
constructor(private _loginService: LoginService,private _router: Router) {
this.router = _router;
}
onAuthenticate() {
this.submitted = true;
this._loginService.Login().then( function (loginValues) {
if(loginValues.username=="sampleuser" && loginValues.password=="a"){
this.router.navigate(['LandingPage']);
}
else{
alert("Invalid Username or Password!!");
}
});
}
}
LoginService
import {Injectable} from 'angular2/core';
@Injectable()
export class LoginService {
Login(){
return Promise.resolve(login);
}
}
var login={
username:"sampleuser",
password:"a"
}