懒加载模块Angular 7中的单例注入令牌

时间:2018-12-07 07:56:33

标签: angular

我想通过一个帐户服务来设置用户的身份验证。我有“ auth.service”,它负责使用“ account.service”实用程序服务保存用户。验证服务在app.module中提供。应用程序中的每个服务都实现一个特定的接口,因此无论我在哪里注入服务,我都使用工厂提供的注入令牌来提供每个服务实例。

service.provider.ts

export const UtilitiesServiceProvider = new InjectionToken<UtilitiesService>(
"UtilitiesServiceProvider",
{ providedIn: "root", factory: () => new UtilitiesService() }
);

export const AccountServiceProvider = new InjectionToken<AccountService>(
"AccountServiceProvider",
{ providedIn: "root", factory: () => new AccountService() }
);

export const AuthServiceProvider = new InjectionToken<AuthService>(
"AuthServiceProvider",
{ providedIn: "root", factory: () => new AuthService(inject(UserRepository), inject(AccountService), inject(UtilitiesService)) }
);

auth.service.ts

@Injectable()
export class AuthService implements IAuthService {

   constructor(
    @Inject(UserRepositoryProvider) private userRepository: IUserRepository,
    @Inject(forwardRef(() => AccountServiceProvider)) private accountService: IAccountService,
    @Inject(forwardRef(() => UtilitiesServiceProvider)) private utilitiesService: IUtilitiesService) {        
}

   public isUserLoggedIn(): Observable<boolean> {
    return this.userRepository.getUser()
        .pipe(
            map((data: IUserDto) => {
                if (isNil(data)) {
                    return false;
                }

                this.accountService.setUser(data);

                return true;
            })                
        );
    }
}

在“ isUserLoggedIn”身份验证服务方法内部,用户已保存到帐户服务中。我想从我的应用程序内部的延迟加载模块中声明的“标头”组件中获取用户详细信息。

header.component.ts

export class HeaderComponent implements OnInit {

     constructor(
    @Inject(ReportingRepositoryProvider)
    private reportingRepository: IReportingRepository,   
    @Inject(forwardRef(() => AccountServiceProvider))
    private accountService: IAccountService) {
    }

   public test() {
      //accountService instance gets its own scope
      const x = this.accountService.getUser();
   }

}

account.service.ts

@Injectable()
export class AccountService implements IAccountService {
private user: IUserDto = null;

public setUser(user: IUserDto): void {
    this.user = user;
}

public getUser(): IUserDto {
    return this.user;
}    

 }

问题在于,因为从懒惰加载的模块声明了“ header”组件,accountService获得了自己的作用域,而通过getUser()“ header's”组件方法进行访问时,AccountService的私有“ user”属性为null。

我试图删除注入令牌并仅提供AccountService而不使用AppModule的接口,并且一切正常。延迟加载的模块组件中的AccountService实例也相同。有没有办法在我的整个应用程序中提供相同的注入令牌实例?

0 个答案:

没有答案