Advertisement
Guest User

Untitled

a guest
Dec 5th, 2016
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.24 KB | None | 0 0
  1. @NgModule({
  2. imports: [
  3. BrowserModule,
  4. HttpModule,
  5. ReactiveFormsModule,
  6. MyModule
  7. ],
  8. providers: [
  9. AuthguardService,
  10. LoginService
  11. ],
  12. declarations: [
  13. AppComponent,
  14. ],
  15. exports: [
  16. ],
  17. bootstrap: [AppComponent],
  18. })
  19. export class AppModule { }
  20.  
  21. import { Injectable } from '@angular/core';
  22. import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
  23.  
  24. import { LoginService } from './mymodule/login';
  25.  
  26. @Injectable()
  27. export class AuthguardService implements CanActivate {
  28.  
  29. constructor(
  30. private service: LoginService,
  31. private router: Router
  32. ) { }
  33. canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean{
  34. let url: string = state.url;
  35. return this.checkLogin(url);
  36. }
  37.  
  38. private checkLogin(url: string){
  39. debugger;
  40. if (this.service.isLoggedIn()) {
  41. console.log(this.service.loggedIn);
  42. return true;
  43. } else {
  44. console.log(this.service.loggedIn);
  45. this.router.navigate(['/']);
  46. return false;
  47. }
  48. }
  49. }
  50.  
  51. import { Injectable } from '@angular/core';
  52. import { Http, Response, Headers, RequestOptions } from '@angular/http';
  53. import { Observable } from 'rxjs/Observable';
  54. import 'rxjs/add/operator/map';
  55.  
  56. @Injectable()
  57. export class LoginService {
  58. loggedIn: boolean = false;
  59. constructor(
  60. http: Http
  61. ){}
  62.  
  63. login(username: string, password: string){
  64. let header = new Headers({
  65. 'Content-Type': 'application/json',
  66. 'Accept': 'application/json',
  67. });
  68. return this.http.post(
  69. 'http://localhost/api/login',
  70. JSON.stringify({login:username,password:password}),
  71. {headers: headers}).map((res: Response)=>{
  72. this.loggedIn = true;
  73. return res.json();
  74. })
  75. .catch(this.handleError);
  76. }
  77. logout(){
  78. this.loggedIn = false;
  79. }
  80. isLoggedIn(){
  81. if(this.loggedIn == true){
  82. return true;
  83. } else {
  84. return false;
  85. }
  86. }
  87. private handleError(error: Response) {
  88. console.error(error);
  89. return Observable.throw(error.json().error || 'Server error');
  90. }
  91. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement