简体   繁体   English

如何从nestjs中的另一个文件导入变量?

[英]How to import a variable from another file in nestjs?

I try to import a variable from another file but i don't success.我尝试从另一个文件导入变量,但没有成功。 In my first file I have :在我的第一个文件中,我有:

import { Injectable } from '@nestjs/common';

@Injectable()
export class Hello {
}
var varhello = "hi";

And in the other where i want to add varHello I have:在另一个我想添加 varHello 的地方,我有:

import { Injectable } from '@nestjs/common';
import * as hello from "./Hello";

@Injectable()
export class AppService {
  getHello(): any {
    console.log(hello.Hello)
  }
}

At least my console.log return something : [class Hello], but I want it to return the text "hi".至少我的 console.log 返回了一些东西:[class Hello],但我希望它返回文本“hi”。 Anyone know how to fix my problem?有谁知道如何解决我的问题?

Best practice would be to keep the greeting variable private inside hello class and have public methods for returning/modifying property that can be used by other classes, after that inject Hello service wherever you need it and call that method.最佳实践是将 greeting 变量保持在 hello 类中私有,并具有返回/修改可由其他类使用的属性的公共方法,然后在任何需要它的地方注入 Hello 服务并调用该方法。

import { Injectable } from '@nestjs/common';

@Injectable()
export class Hello {
  private _greeting: string = 'Hi';

  get greeting(): string {
    return this._greeting;
  }
}

and then in your service:然后在您的服务中:

import { Inject, Injectable } from '@nestjs/common';

import { Hello } from './Hello';

@Injectable()
export class AppService {
  @Inject()
  protected hello: Hello;

  getHello(): void {
    console.log(this.hello.greeting);
  }
}

Or if you want you could export a const variable like this或者,如果你愿意,你可以像这样导出一个 const 变量

// Hello.ts file
export const hello = 'Hi';

And in your service you'll just import it在您的服务中,您只需导入它

import { Injectable } from '@nestjs/common';

import { hello } from './Hello';

@Injectable()
export class AppService {
  getHello(): void {
    console.log(hello);
  }
}

But this way it will be just a const, and you won't be able to overwrite it.但是这样它就只是一个常量,你将无法覆盖它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM