AuthService始终以默认状态注入

时间:2017-05-31 14:52:04

标签: angular

这是我的代码

import {User} from '../models/user';
import {Injectable} from '@angular/core';
import {Http, Headers, RequestOptions, Response} from '@angular/http';
import {AuthHttp} from 'angular2-jwt';
import {Router} from '@angular/router';
import {Config} from '../app.constants';
import {Observable, ReplaySubject} from 'rxjs/Rx';

@Injectable()
export class AuthService {
  public currentUser: ReplaySubject<User> = new ReplaySubject<User>(1);
  public loggedIn = false;
  constructor(public http: Http,
              public authHttp: AuthHttp,
              private router: Router) {
  }

  public setCurrentUser(user: User) {
    this.loggedIn = true;
    this.currentUser.next(user);
  }

}

这是路由

export const routes: Routes = [
  {
    children: [
      {
        component: HomeComponent,
        path: ''
      },
      {
        canActivate: [CanActivateGuard],
        component: UploadComponent,
        path: 'upload',
      },
      {
        component: RegisterComponent,
        path: 'register'
      },
      {
        component: LoginComponent,
        path: 'login'
      },
    ],
    component: WebComponent,
    path: '',
  }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule],
})
export class WebRoutingModule {
}

当使用登录时,此代码将this.loggedIn设置为true

let user = new User(data.user);
this._auth.setCurrentUser(user);

中登录后发生问题

这是我的调试结果

{p {3}}上的

我添加了toggleSearchInput方法console.log(this._auth)

  toggleSearchInput() {
    console.log(this._auth)
    this.searchInputExpanded = !this.searchInputExpanded;
  }

当我点击按钮时,控制台会记录正确的_auth并登录为= true

on web.component.ts我添加了canActivate方法console.log(this._auth)

  public canActivate() {
    console.log(this._auth)
    if ( !this.logged ) {
       this.router.navigate( [ 'login' ] );
    }
    return this.logged;
  }

并且每次我点击上传时检查控制台..它控制台给我auth服务,就像没有发生任何事情一样,即使在登录后,loggedIn = false ...你知道为什么会这样吗?

为什么服务没有改变

1 个答案:

答案 0 :(得分:1)

为每个导入它的模块实例化您的服务。如果要跨多个模块使用服务,则需要输入一个模块(例如SharedModule)并导入,使用.forRoot()导入一次,并在其他模块中以正常方式导入。像这样:

<强> SharedModule

@NgModule({
  imports: [ ..., HttpModule ],
  declarations: [
     ...
  ]
})
export class SharedModule {
  static forRoot(): ModuleWithProviders {
    return {
      ngModule: SharedModule,
      providers: [
        AuthService,
        ...
      ]
    };
  }
}

<强>的AppModule

@NgModule({
  declarations: [ ... ],
  imports: [ ..., SharedModule.forRoot()],
  providers: [ ... ],
  bootstrap: [AppComponent],
  entryComponents: [ ... ]
})
export class AppModule { }

<强> WebModule

@NgModule({
  imports: [ ..., SharedModule ],
  declarations: [...]
})
export class WebModule { }