【问题标题】:How can I change the name of the template that is passed to the @Render decorator in the Interceptor?如何更改在拦截器中传递给 @Render 装饰器的模板名称?
【发布时间】:2021-09-27 13:42:29
【问题描述】:

如何更改在拦截器中传递给@Render 装饰器的模板名称?我需要根据用户的语言将所需的语言环境添加到模板 url。我正在尝试这样做,但它不起作用。我该怎么做?

@Injectable()
export class RenderByLanguageInterceptor implements NestInterceptor {
  constructor(private reflector: Reflector) {}

  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const template = this.reflector.getAllAndOverride<string>(RENDER_METADATA, [
          context.getHandler(),
          context.getClass(),
    ]);

    const lang = context.switchToHttp().getRequest().i18nLang;
    SetMetadata(RENDER_METADATA, `${lang}/${template}`);

    return next.handle();
  }
}

【问题讨论】:

    标签: javascript nestjs nestjs-i18n


    【解决方案1】:

    SetMetadata 是来自 Nest 库的装饰器,作为辅助函数。您需要做的是使用Reflect API 并按照以下方式做一些事情

    Reflect.defineMetadata(
      RENDER_METADATA,
      `${lang}/${tempalte}`,
      context.getClass(),
      context.getHandler()
    );
    

    Reflect 来自reflect-metadata。这应该适当地设置元数据,以便以后可以读取。使用这种方法,您必须确保每次都设置元数据,因为不会回退到 @Render() 装饰器中的原始元数据。

    【讨论】:

    • 问题是我无法获得上下文。 switch 到 Http().GetRequest().i18nlang,好像还没在上下文中,在上下文中出现 i18nLang 后怎么获取呢?
    • i18nlang 什么时候出现在 req 对象上?它是如何填充的?
    • 到 AppModule 导入
    • AppModule 的导入不会影响每个请求的请求对象。 AppModule 仅用于定义应用程序中使用的模块、提供程序和控制器
    • return next.handle().pipe( map((data) => { const lang = context.switchToHttp().getRequest().i18nLang; console.log(lang); return data; }), ); - 这就是我可以得到lang的方法。根据用户的语言更改模板路径,我还能如何解决我的问题?
    猜你喜欢
    • 1970-01-01
    • 2012-03-01
    • 2016-06-12
    • 2013-08-21
    • 2019-11-20
    • 2021-08-04
    • 1970-01-01
    • 1970-01-01
    • 2018-05-30
    相关资源
    最近更新 更多