首页 > 解决方案 > Spartacus 扩展 AuthService

问题描述

是否可以扩展 Auth Service 并为其添加其他参数?

目前正在尝试扩展但遇到如下错误:

src/app/service/auth/auth-extend.service.ts(15,3) 中的错误:错误 TS2416:“AuthExtendService”类型中的属性“授权”不可分配给基本类型“AuthService”中的相同属性。

类型 '(userId: string, password: string, countryCode: string, businessType: string) => void' 不可分配给类型 '(userId: string, password: string) => void'。

src/app/service/auth/auth-extend.service.ts(21,7): error TS2345: Argument of type '{ userId: string; 密码:字符串;国家代码:字符串;业务类型:字符串;}' 不能分配给 '{ userId: string; 类型的参数;密码:字符串;国家代码:字符串;业务类型:字符串;}'。

对象字面量只能指定已知属性,但类型 '{ userId: string; 中不存在 'businessType' 密码:字符串;国家代码:字符串;业务类型:字符串;}'。你的意思是写“businessType”吗?"

这里的任何人都试图这样做,比如添加新参数。

标签: oauthauthorizespartacus-storefront

解决方案


Typescript 不支持这种开箱即用的重载。一种方法是使用可选参数,例如:

export class AuthExtendService extends AuthService {
  authorize(userId: string, password: string, businessType?: string): void {
    console.log(businessType);
    this.store.dispatch(
      new AuthActions.LoadUserToken({
        userId: userId,
        password: password,
      })
    );
  }  
}

这就是您应该添加额外参数的方式。


推荐阅读