Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- @NgModule({
- imports: [
- BrowserModule,
- HttpModule,
- ReactiveFormsModule,
- MyModule
- ],
- providers: [
- AuthguardService,
- LoginService
- ],
- declarations: [
- AppComponent,
- ],
- exports: [
- ],
- bootstrap: [AppComponent],
- })
- export class AppModule { }
- import { Injectable } from '@angular/core';
- import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
- import { LoginService } from './mymodule/login';
- @Injectable()
- export class AuthguardService implements CanActivate {
- constructor(
- private service: LoginService,
- private router: Router
- ) { }
- canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean{
- let url: string = state.url;
- return this.checkLogin(url);
- }
- private checkLogin(url: string){
- debugger;
- if (this.service.isLoggedIn()) {
- console.log(this.service.loggedIn);
- return true;
- } else {
- console.log(this.service.loggedIn);
- this.router.navigate(['/']);
- return false;
- }
- }
- }
- import { Injectable } from '@angular/core';
- import { Http, Response, Headers, RequestOptions } from '@angular/http';
- import { Observable } from 'rxjs/Observable';
- import 'rxjs/add/operator/map';
- @Injectable()
- export class LoginService {
- loggedIn: boolean = false;
- constructor(
- http: Http
- ){}
- login(username: string, password: string){
- let header = new Headers({
- 'Content-Type': 'application/json',
- 'Accept': 'application/json',
- });
- return this.http.post(
- 'http://localhost/api/login',
- JSON.stringify({login:username,password:password}),
- {headers: headers}).map((res: Response)=>{
- this.loggedIn = true;
- return res.json();
- })
- .catch(this.handleError);
- }
- logout(){
- this.loggedIn = false;
- }
- isLoggedIn(){
- if(this.loggedIn == true){
- return true;
- } else {
- return false;
- }
- }
- private handleError(error: Response) {
- console.error(error);
- return Observable.throw(error.json().error || 'Server error');
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement