Eduard Arevshatyan
Eduard Arevshatyan

Reputation: 678

canActivated in angular2

I create some application in angular 2 with typescript and add authentification.

I create authguard for my routing file:

@Injectable()
export class AuthGuard implements CanActivate {

public router: Router;
public serverThisLogin: ServerDataComponent;

constructor(router: Router) {
    this.router = router;
}

public canActivate(): boolean {
    if (this.serverThisLogin.isLogin)  {
        return true;
    }
    this.router.navigate(["/login"]);
    return false;
}
}

And this is isLogin() function:

 public isLogin (username: string, password: string): Observable<boolean> {
     return this.http.post( authURL + loginURL,
                             JSON.stringify({  password, username }))
     .map((response: Response) => {
         if (response.status === 200) {
             return true;
         } else {
             return false;
         }
     });
 }

I add authguard in my route file:

{ canActivate: [AuthGuard], component: LaskComponent, path: "table_per" }

And now, when i load this page localhost/table_per i have this error: TypeError: Cannot read property 'isLogin' of undefined. I really understand why it happens.

Upvotes: 0

Views: 73

Answers (1)

Lo&#239;cR
Lo&#239;cR

Reputation: 5039

You just need to inject the service to be able to use it, take profit of Typescript possibility to use the DI container properly:

@Injectable()
export class AuthGuard implements CanActivate {

public router: Router;
public serverThisLogin: ServerDataComponent;

constructor(private router: Router, private serviveThisLogin: ServerDataComponent) {}

public canActivate(): boolean {
    if (this.serverThisLogin.isLogin) {
        return true;
    }

    this.router.navigate(["/login"]);
    return false;
    }
}

Also, you could simplify your condition from this:

if (response.status === 200) {
             return true;
         } else {
             return false;
         }

To this:

return response.status === 200;

Upvotes: 1

Related Questions