Reputation: 409
I have 2 components in my angular app (Home and Login). Login is the default page and once logged in I want to navigate to Home.
I have a app.router.ts which looks like :-
import { LoginComponent } from './login/login.component';
import { ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
export const router: Routes = [
{ path: '', redirectTo: 'login', pathMatch: 'full'},
{ path: 'home', component: HomeComponent},
{ path: 'login', component: LoginComponent}
];
export const routes: ModuleWithProviders = RouterModule.forRoot(router);
I have a service which looks like:-
import { Injectable } from '@angular/core';
import 'rxjs/add/operator/map';
import { Observable } from 'rxjs/Observable';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
@Injectable()
export class NetworkService {
private _url: string = "http://localhost:4200/api/login";
public _userloggedin: boolean = false;
constructor(private _http:Http) {
}
login(data): Observable<Object> {
let encoded_data = JSON.stringify(data);
let headers = new Headers({ 'Content-Type': 'application/json;charset=utf-8' });
let options = new RequestOptions({ headers: headers });
return this._http.post(this._url, encoded_data, options)/*.map(
(res: Response) => res.json() || {}
)*/;
}
}
In my login component, I have an method hooked up with the submit button which does the call to the backend api for login. Login component looks like :-
import { Component, OnInit } from '@angular/core';
import { NetworkService } from './../services/network.service';
import { Router } from '@angular/router';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css'],
providers : [NetworkService]
})
export class LoginComponent implements OnInit {
constructor(private networkservice : NetworkService, private router: Router) {
}
ngOnInit() {
}
onSubmit(value:any){
/*
network call and if credentials match set variable in service to true;
*/
this.networkservice._userloggedin = true;
this.router.navigate(['/home']);
}
else{
}
}
}
Finally in my home component, I check the value of the "_userloggedin" of service. Based on the value of this variable I perform routing (if true than show homepage else navigate back to "login page").
import { NetworkService } from './../services/network.service';
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css'],
providers : [NetworkService]
})
export class HomeComponent implements OnInit {
constructor(private networkservice : NetworkService,private router: Router) { }
ngOnInit() {
if(this.networkservice._userloggedin != true){
this.router.navigate(['/login']);
}
}
}
The problem is that the in the home.component.ts, the value of the _userloggedin is always "false" (which is the default value).
I want to know if this is the right way of doing "condition based routing". If yes, the how do I get it working.
Upvotes: 1
Views: 5066
Reputation: 16
Addition to the above answers.
Yes, the right way to implement this functionallity is using the Angular Route Guards.
but the solution to your problem "The problem is that the in the home.component.ts, the value of the _userloggedin is always "false" (which is the default value).", is to provide the dependency "NetworkService" into a common module ( best palace is the App module), not into indivisual components.
You might face the same issue while implementing the Route Guard if the service is not provided at the right place.
Upvotes: 0
Reputation: 19640
Make use of Angular 2 Guards . which has two methods canActivate
and canDeactivate
which fires onece when the component is about to load and when the component is about to be left or destroyed .
You can check the values and then depending upon the value you can navigate to a different page using .navigate method.
A example can be found on this link
https://rahulrsingh09.github.io/AngularConcepts
Advanced Concepts - > Angular Guards
Upvotes: 0
Reputation: 424
You can use CanActive Guards for conditional routing.
https://angular.io/docs/ts/latest/api/router/index/CanActivate-interface.html
Angular2: Global Guard (user has to be logged in always)
Upvotes: 2