Angular2服务未作为单例注入 [英] Angular2 service not being injected as singleton

查看:78
本文介绍了Angular2服务未作为单例注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我定义了以下服务:

@Injectable()
export class UserService {

private _users: User[] = []
private _currentUser:User;

///Creates an instance of the Angular2 Http Service 
 constructor(private _http: Http) {console.log("in the constructor"; }

这是从登录组件中调用的:

This is called from the login component:

@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
 })
export class LoginComponent implements OnInit {
returnUrl: string;

constructor(private _userService: UserService,
          private route: ActivatedRoute,
          private router: Router)   { }

 validateUser(username: string, password: string): boolean {
  var loggedOnUser = this._userService.checkLogin(username, password);
  ...//check if logged on
 this.router.navigate([this.returnUrl]);

  return true;
 }

但是,成功登录后,它将重定向到本地路由,并且身份验证保护启动了一个新的用户服务实例,这是因为它是一个新实例,为身份验证的用户返回了未定义的

However, when there is a successful login, it redirects to the home route and the authentication guard starts up a new instance of the user service, which because it is a new instance returns undefined for the authenticated user

@Injectable()
export class AuthGuard implements CanActivate {

constructor(private router: Router, private _userService: UserService) { }

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {

    if (this._userService.getAuthenticatedUser()) //is undefined?????
    {
        return true;
    }

    // not logged in so redirect to login page with the return url
    this.router.navigate(['/login'], { queryParams: { returnUrl: state.url    }});
    return false;
}
}

我的模块声明如下:

@NgModule({
 declarations: [
AppComponent,
LoginComponent,
HomeComponent,
ManageUsersComponent,
StandingDataComponent
 ],
 imports: [
BrowserModule,
FormsModule,
HttpModule,
AppRoutingModule
 ],
providers: [AuthGuard,UserService],
bootstrap: [AppComponent]
})
export class AppModule { }

我的路由类如下:

const appRoutes: Routes = [
{path: '', component: HomeComponent, canActivate:[AuthGuard]},    
{ path: 'login', component: LoginComponent },
{path: 'home', 
component:HomeComponent, canActivate:[AuthGuard],
children: [{path: 'manageusers', component: ManageUsersComponent, outlet: 'innerPage'},
            {path: 'standingdata', component: StandingDataComponent, outlet: 'innerPage'}]
}, 
// otherwise redirect to home
{ path: '**', redirectTo: '' }];

@NgModule({
    imports: [RouterModule.forRoot(appRoutes)],

exports: [RouterModule]
})
export class AppRoutingModule { }

用户服务构造函数代码在登录页面被点击以及身份验证成功时均会触发.

The user service constructor code is firing both when the login page is hit, and when a successful authentication occurs.

我的理解是,当在组件和模块中都定义UserService时,会发生这种问题,但是在我的情况下,模块是唯一定义此问题的地方.

My understanding is that this kind of problem happens when UserService is defined in both the component and the module, but in my case the module is the only place where this is defined.

推荐答案

在以下stackoverflow中找到了解决方案:

The solution was found in the following stackoverflow:

Angular2 router.navigate刷新页面

这使我在Internet Explorer中对其进行了测试,该工作正常,但无法在Chrome中正常工作

This led me to test it in Internet Explorer, which worked OK (it was not working in Chrome)

原来,执行以下行时,整个页面都在刷新:

It turned out that the entire page was refreshing when the following line was executed:

this.router.navigate([this.returnUrl]);

这是导致用户服务重新加载的原因,因为按钮上没有 type 类型,Chrome的默认操作是将按钮单击视为提交.

Which was causing the user service to reload again, because without a type on the button, Chrome's default action was to treat the button click as a submit.

解决方法是将标记 type ="button" 添加到html中的登录按钮

The fix was to add the tag type="button" to the login button in the html

<button type="button" class="btn btn-primary"(click)="validateUser(username, password)">Login</button>

它现在可以在所有浏览器中使用.

It now works in all browsers.

这篇关于Angular2服务未作为单例注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆