【发布时间】:2017-03-11 03:01:09
【问题描述】:
我正在使用带有打字稿的 angular2。在其中一项服务中,我正在设置并获取如下变量的值:
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;
}
}
但是当我尝试使用 getLoggedInStatus() 获取值时,我每次都不确定。 为什么会这样?
在这里设置
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);
})
}
}
}
到达这里
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;
}
}
【问题讨论】:
-
您在一个组件中使用
setLoggedInStatus,在另一个组件中使用getLoggedInStatus,对吗? -
你是如何设置和获得的?
-
您可能在服务的另一个实例上调用它。如果您不发布重现问题的示例,就无法说出原因。
-
@camaron:在不同的组件中是的
-
@BhushanGoel 好的,你的问题是 JB Nizet 指出的。您必须确保
UserProfileService仅由一个 NgModule 提供,没有其他地方提供。
标签: angular typescript