Search code examples
spartacus-storefront

Can't override UserAuthenticationTokenService service


I'm trying to add custom logic for login page, for that as described here I try to override UserAuthenticationTokenService service. I want to add custom logic to this method:

loadToken(userId: string, password: string): Observable<UserToken>;

But when I try to import this class definition it comes from

import {UserAuthenticationTokenService} from '@spartacus/core/src/auth/services/user-authentication/user-authentication-token.service';

After this auto import project cannot be compiled with error:

ERROR in ./src/app/services/services.module.ts Module not found: Error: Can't resolve '@spartacus/core/src/auth/services/user-authentication/user-authentication-token.service' in '/home/gyerts/PycharmProjects/fiver/e5p-client/src/app/services'

What I'm doing wrong?


Solution

  • While it's true that it's not being exported directly in Spartacus 2.x, I have found that it is still available. If you look at the compiled spartacus-core.d.ts file, you will see that UserAuthenticationTokenService is being exported under a gibberish name:

    export { UserAuthenticationTokenService as ɵbj } from './src/auth/services/user-authentication/user-authentication-token.service';
    

    While this is probably not the best idea, I have found that you can actually import this in your own code. You can also rename it back to the original name for legibility:

    import { ɵbj as UserAuthenticationTokenService } from '@spartacus/core';
    

    I have used this myself on my current project and it seems to work fine:

    @Injectable({
      providedIn: 'root'
    })
    export class MyUserAuthenticationTokenService extends UserAuthenticationTokenService {}
    
    import { NgModule } from '@angular/core';
    import { CommonModule } from '@angular/common';
    import { MyUserAuthenticationTokenService } from './services/my-user-authentication-token.service';
    import { ɵbj as UserAuthenticationTokenService } from '@spartacus/core';
    
    
    @NgModule({
      declarations: [],
      imports: [
        CommonModule,
      ],
      providers: [
        { provide: UserAuthenticationTokenService, useExisting: MyUserAuthenticationTokenService }
      ]
    })
    export class MyAuthModule {
    }