I am using angular2 with typescript. In one of the service I am setting and getting the value of a variable like this:
import {Injectable} from '@angular/core';
@Injectable()
export class UserProfileService {
isLoggedIn: boolean;
constructor() {
}
setLoggedInStatus(status) {
console.log('status: ', status);
this.isLoggedIn = status;
console.log('this.isLoggedIn : ', this.isLoggedIn) //setting to true or false here
}
getLoggedInStatus() {
return this.isLoggedIn;
}
}
but when I am trying to get the value using getLoggedInStatus(), I am getting undefined each time. Why is this happening ?
setting here
import {Component} from '@angular/core';
import {FormControl, FormGroup, Validators} from '@angular/forms';
import {SharedService} from '../../shared.service';
import {UserProfileService} from '../../authComponent/login/user-profile.service';
@Component({
selector: 'login',
templateUrl: 'app/components/authComponent/login/login.component.html',
providers: [SharedService, UserProfileService]
})
export class LoginComponent implements OnInit {
matched: boolean = false;
constructor(private sharedService: SharedService, private userService: UserProfileService) {
}
ngOnInit() {
this.myForm = new FormGroup({
email: new FormControl('', [Validators.required]),
password: new FormControl('', [Validators.required])
})
}
submit({value, valid}) {
if (!valid) {
return;
}
else {
this.sharedService.getData('users')
.subscribe(result => {
console.log('result: ', result, 'value passed: ', value)
result.forEach((record) => {
if ((record.email == value.email && record.password == value.password) && !this.matched) {
this.matched = true;
}
else {
this.matched = false;
}
});
if (!this.matched)
console.log('wrong credentials entered');
this.userService.setLoggedInStatus(this.matched);
})
}
}
}
getting here
import {Injectable} from '@angular/core';
import {
CanActivate,
CanActivateChild,
Route,
Router,
ActivatedRouteSnapshot,
RouterStateSnapshot
} from '@angular/router';
import {UserProfileService} from './authComponent/login/user-profile.service';
@Injectable()
export class CanActivateAuthGuard implements CanActivate, CanActivateChild {
constructor(private userProfileService: UserProfileService, private router: Router) {
}
canActivateChild(next: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
return this.canActivate(next, state);
}
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
console.log('this.userProfileService.getLoggedInStatus: ', this.userProfileService.getLoggedInStatus())
if (this.userProfileService.getLoggedInStatus()) {
return true;
}
this.router.navigate(['/login'], {queryParams: {redirectTo: state.url}});
return false;
}
}
setLoggedInStatusin one component andgetLoggedInStatusin another component right?UserProfileServiceis provided by only one NgModule and no other place.