The example only shows loading of 1 locale which is bg.
How are we able to load all the locale so that we can change the locale dynamically. Thanks in advance!
http://plnkr.co/edit/Ucx0SlcmBfN9TRjrS5Ad?p=preview Plunker
[Short answer]
You can't change the locale of the Angular application dynamically, without recreating the module/component.
[Long version]
The locale of the Angular component is determined by the LOCALE_ID, which is injected through the Angular DI system. Considering the fact the Angular uses constructor based dependency injection, the component needs to be recreated in order to receive new LOCALE_ID value.
That being said, the only feasible solution to have components/modules with different locales is to wrap them with high order component that will provide different LOCALE_ID:
#Component({
selector: 'bg',
providers: [{
provide: LOCALE_ID,
useValue: 'bg-BG'
}, {
provide: IntlService,
useFactory: (localeId: string) => new CldrIntlService(localeId),
deps: [LOCALE_ID]
}],
template: `
<ng-content></ng-content>
`
})
export class BGComponent {
}
Here is runnable demo:
http://plnkr.co/edit/gmAWVLD1Yzn353QA1eDj?p=preview
Please note, that the plunker demonstrates how to place components with different locale on one page. As I mentioned, fully dynamic change of the locale is not possible (excluding the all possible hacks, of course). If there is a good solution out there using LOCALE_ID, I'd be more than happy to see it.
Related
i am a new software developer. I don't have much software background, but I'm trying to learn as much as I can. Is there anyone who has done influxdb operation with nestjs before? If yes, can you share your previous experiences?
Thank you in advance for reading and replying.
Your going to face many hardships if you consider using nestjs... Maybe im wrong and your underselling yourself, but if you are asking if its possible to connect a database to your backend then nest is surly going to be WAYYYYY WAYYYYY WAYYYYY to complex -> to be able to figure stuff out... Not that you CANT but you might want to consider
Express first just to get an understanding of how a backend works -> without having to plan out all your dtos' controllers services yatta yatta yatta.. you can do all of the same stuff with express, infact the developers used express to make next -> and then added a whole lot of enterprise level stuff that doesnt come standard with express.
plus if you are new to coding then typescript might be a bit much. very sorry if this was not what you were looking for Im not trying to steer you in any particular direction. but I spend 12 hours - 36 hours sometimes trying to figure things out that I already had working before ... the injection and all that come with nest is good , but if you dont know why you need it , then its going to be very hard to actually learn the concepts.
its alot easier to teach someone how to drink water if theyre thirsty .
otherwise you are just going to spend alot of time that could of went into learning the things that are a prerequisite of nest
strong es6 / ts is def a must
the es6 part is more important imo because dealing with everything async for instance and the way everything is formatted its very confusing without a strong grasp of whats going on behind the scenes.
--- as im sure your going to want to find out the hard way -> and i dont blame you if you can get through it you will be a much stronger person =) but here try this on for size.
https://www.npmjs.com/package/nest-influxdb
import { Module } from "#nestjs/common";
import { InfluxDbModule, InfluxModuleOptions } from "nest-influxdb";
import { UtilsModule } from "./utils/utils.module";
import { ConfigService } from "./utils/config/config.service";
#Module({
imports: [
InfluxDbModule.forRootAsync({
imports: [UtilsModule],
inject: [ConfigService],
useFactory: async (
config_servie: ConfigService
): Promise<InfluxModuleOptions> => {
return {
host: config_servie.get("INFLUX_HOST")
};
}
}),
BlogModule
],
controllers: [AppController],
providers: [AppService]
})
export class AppModule {}
this will go in your root level module file -> then you will use the for feature method for the specific thing inside your root database
check the nest docs for how it works with other databases then try to connect the dots with that above package
Nest can't resolve dependencies of the MailService (MailerService, ?, CreateSendMailDto). Please make sure that the argument EmailRepository at index [1] is available in the MailModule context.
Potential solutions:
- If EmailRepository is a provider, is it part of the current MailModule?
- If EmailRepository is exported from a separate #Module, is that module imported within MailModule?
#Module({
imports: [ /* the Module containing EmailRepository */ ]
})
Error: Nest can't resolve dependencies of the MailService (MailerService, ?, CreateSendMailDto). Please make sure that the argument EmailRepository at index [1] is available in the MailModule context.
Potential solutions:
- If EmailRepository is a provider, is it part of the current MailModule?
- If EmailRepository is exported from a separate #Module, is that module imported within MailModule?
#Module({
imports: [ /* the Module containing EmailRepository */ ]
})
I'm new to nestjs thou not too experienced with nodejs. Pls i need someone to help me understand the context of module export and providers. I don't really know what to export, import, provied or put in controller, i understand some few stuff but i seek full undersanding of how and what is really happening there. Thanks
You didn't add the code producing the error, but I'll try to explain it in simple terms, assuming the following scenario:
You have two resources, Vehicle & Driver, and you want to use DriverService in VehicleService.
Solution:
Export DriverService from driver.module.ts
Then import DriverModule in vehicle.module.ts
#Module({
controllers: [DriverController],
providers: [DriverService],
exports: [DriverService]
})
#Module({
imports:[DriverModule]
controllers: [VehicleController],
providers: [VehicleService],
})
You can visit the NestJs docs for more info.
How does the framework manage the lifetime of DynamicModules?
The NestJs documentation on Modules states that:
In Nest, modules are singletons by default, and thus you can share the same instance of any provider between multiple modules effortlessly.
How can you share multiple dynamic module instances between modules?
The NestJs documentation on DynamicModules states that:
In fact, what our register() method will return is a DynamicModule. A dynamic module is nothing more than a module created at run-time, with the same exact properties as a static module, plus one additional property called module.
How can you manage/change the scope of DynamicModules? For example, changing them from behaving transitively to as a singleton. Defining their injection token, retrieving them on demand, etc.
How does the framework manage the lifetime of DynamicModules?
Generally speaking, like it does any other module. A dynamic module is just a special name for a module configuraed by a function and represented by an object. The end result is usually something like
{
module: SomeModuleClass,
imports: [Imports, For, The, Module],
providers: [SomeProviderToken, SomeProviderService, ExtraProvidersNeeded],
exports: [SomeProviderService],
}
Pretty much the same kind of thing you'd see in an #Module() decorator, but configured via a function that possibly uses DI instead of just written directly
How can you share multiple dynamic module instances between modules?
I might need a bit of clarification here, but I'll be happy to edit my answer with more detail once I know what's the goal here, or what you're trying to do.
How can you manage/change the scope of DynamicModules? For exmaple, changing them from behaving transitively to as a singleton. Defining their injection token, retrieving them on demand, etc.
The easiest option for sharing your configuration (besides making the module #Global()) is to make a wrapper module that re-exports the dynamic module once it has been configured.
Example: Let's say we have a dynamic FooModule that we want to pass application to, to designate the name of the application, and we want to re-use that module in several other places
#Module({
imports: [
FooModule.forRoot(
{ application: 'StackOverflow Dynamic Module Scope Question' }
)
],
exports: [FooModule],
})
export class FooWrapperModule {}
Now instead of importing FooModule.forRoot() again in multiple places, we just import FooWrapperModule and get the same instance of FooService with the configuration originally passed.
I do want to mention that by convention, DynamicModule.forRoot/Async() usually implies single time registration in the RootModule and usually has a #Global() or isGlobal: true config attached to it somewhere. This isn't always the case, but it holds relatively true.
DynamicModule.register/Async() on the other hand, usually means that we are configuring a dynamic module for this module only and it can be reconfigured elsewhere to have it's own separate config. This can lead to cool setups where you can have multiple JwtService instances that have different secret values for signing (like for an access and refresh token signing service).
Then there's DynamicModule.forFeature() which is like register in that it is at a per module basis, but usually it uses config from the forRoot/Async() call that was already made. The #nestjs/typeorm module, mikro-orm/nestjs module, and #ogma/nestjs-module module are three separate examples I can think of that follow this pattern. This is a great way to allow for general configuration at the root level (application name, database connection options, etc) and then allow for scoped configuration at the module level (what entities will be injected, logger context, etc)
Taking configuration as an example, the Nest.js documentation advocates registering Config Modules and injecting them into other modules in a dependency injection way.
The benefits are obvious, and the dependencies and code are clear, but what if I have a nest.js project that needs to invoke the configuration information at startup? This actually caused me trouble.
My idea is to use a store (actually a closure) to manage all the variables that might be needed globally, the client-side link objects, registered at startup, and introduced when needed.
When corresponding variables are registered in this way, they can be introduced anywhere. The drawback is that you need to manage dependencies yourself.
With the above concept design of demo: https://github.com/sophons-space/nest-server.
Please e help me correct, I am still a rookie.
If you want to use Nest flow it should be defined in the configuration file
// app.module.ts
import configuration from './config/configuration';
imports: [
// first import as first initialization
ConfigModule.forRoot({
isGlobal: true, // to get access to it in every component
load: [configuration],
}),
]
...
// configuration.ts
export default (): any => {
return {
someGlobalConfigVariable: parseInt(process.env.PORT, 10) || 3000,
};
};
Create a file global.service.ts (inside a folder you can name it utils or whatever) & put the code bellow
export class GlobalService{
static globalVar: any;
}
Set value to the globalVar
GlobalService.globalVar = 'some value';
Get value from globalVar
console.log(GlobalService.globalVar);
N.B. Don't forget to import GlobalService wherever you want to use.
The way you can approach this is similar to how NestJS libraries or integrations usually handle configuration; using a method on the base module.
main.ts
import { NestFactory } from '#nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
// Note the `configure`-method
const app = await NestFactory.create(AppModule.configure({
myConfig: 'value',
});
await app.listen(3000);
}
bootstrap();
app.module.ts
import { DynamicModule } from '#nestjs/common';
export class AppModule {
static configure(config): DynamicModule {
return {
module: AppModule,
providers: [{ provide: 'CONFIG', useValue: config }],
// ....
}
}
}
You can use the general NodeJS approach
global.SomeGlobalVariableName = 'SomeGlobalVariableValue';
console.log(SomeGlobalVariableName);
Approach I used is using my config variables in yaml files and then getting those variables or objects wherever I want in my Nestjs project using config package. e.g in default.yml file
key: value
and then in file where I want to use this
import config from 'config';
let value = config.get<string>('key');
you can take this pkg from this npmjs link here
Why not go with more NestJs way i.e. with provide instance scope?
Most of the answers posted here are correct and easy to implement but I have a more generic way to define that variable that fits well in NestJs (Nestjs Scope and Dependency Injection flow). I would be happy to share the sample code, if required
Steps
Create a provider
Add a private instance variable to this provider - instead of a class variable (i.e. static variables) use an instance variable as NestJs automatically (by default) manages the instance of its providers in a singleton way i.e. a single instance of the provider is shared across the entire application. Read more about scopes here
Add get/set and other methods for that variable
Inject that provider wherever you need the global variable (instance variable of the provider(per instance).
Other ways of doing it
Config - preferrable for pre-defined types(like string, number...)
Static variable in util.ts file
Native Global variable - I would not recommend this(explanation is outside the scope of the question)
Recently I wrote for myself a demo-app (full code: https://github.com/aversilov/parley-fork) based on this Ahamed Foysal's example (https://www.codementor.io/foysalit/rest-api-with-mongodb-and-nest-js-hto6x5120). As you know NestJS is a very young framework and there are catastrophicaly small number of tutorials & demo-apps for learn it.
So, I create all files in the project, run mongod in separate terminal window, and run app:
npm run start
But the app is crashed with:
Error output
P.S. I checked - circular references in my codebase don't exists (Vue + typescript - TypeError: Object prototype may only be an Object or null: undefined).
Any help would be greatly appreciated.
In database.module.ts do a
#Module({
components: [...databaseProviders],
exports: [...databaseProviders],
})
export class DatabaseModule {}
three dots are required
Then in posts.module.ts
#Module({
imports: [DatabaseModule],
controllers: [PostsController],
components: [PostsService, ...postsProviders],
})
export class PostsModule {}
again three dots are required
in posts.providers.ts replace DB_CONNECTION with DB_PROVIDER
Why three dots ? If you will look in posts.providers.ts it exports an array, and you want your module to import each provider separately, not the array.