ng-select-ng-select has no exported member 'NG_SELECT_DEFAULT_CONFIG' - angular-ngselect

Migrating to the latest package results in the build error.
ERROR in src/app/global.module.ts:106:13 - error TS2304: Cannot find name 'NG_SELECT_DEFAULT_CONFIG'.
106 provide: NG_SELECT_DEFAULT_CONFIG,
providers: [
{
provide: NG_SELECT_DEFAULT_CONFIG,
useValue: {
notFoundText: 'Not found',
loadingText: 'Processing',
placeholder: 'Please input'
}
}
]
Any advice and insight is appreciated.

NG_SELECT_DEFAULT_CONFIG was removed. You can set the config by injection NgSelectConfig.
constructor(private config: NgSelectConfig) {
this.config.notFoundText = 'Custom not found';
this.config.loadingText = 'Custom loadingText';
this.config.placeholder = 'Custom placeholder';
}
There's also an example on there github page:
https://github.com/ng-select/ng-select

Related

NestJS Repository seems to be injected but is in-fact empty?

I'm currently working on an API with NestJS and Sequelize, and it seems that there is a problem when injecting the repository.
For context, when the service calls this.repo.findByKey the function is undefined and the program fails, but when inspecting with VSCode's debugger, the proptotype had the function inside of it.
Here is a reproduction of the source :
// service.ts
#Injectable()
export class Service {
constructor(
#Inject('REPOSITORY') private repo: IRepository
) {
super();
}
async getByCode(code: string) {
console.log(this.repo); >> [class Repository extends BaseRepository]
console.log(this.repo.findByKey); >> undefined
return res = await this.repo.findByKey(code); >> this.repo.findByKey is not a function
}
}
// repository.ts
#Injectable()
export class Repository
extends BaseRepository
implements IRepository
{
constructor(
#Inject('DATABASE_HELPER')
databseHelper: DatabaseHelper,
private mapper: CountryMapper,
) {
super(databseHelper);
}
async findByKey(code: string) -> Promise<DTO> {
... never reached
}
}
I cannot find the origim of this problem, is there a dark magician here to help me?
Per request, here is the module configuration :
#Module({})
export class ExampleModule {
static register(typeClass: Type<IService>): DynamicModule {
return {
imports: [
HelperModule,
SequelizeModule.forFeature([Entity]),
],
module: ExampleModule,
providers: [
ExampleMapper,
{
provide: 'REPOSITORY',
useValue: Repository,
},
{
provide: 'SERVICE',
useClass: typeClass,
},
],
controllers: [Controller],
};
}
}
You are injecting the class itself. So this.repo is a constructor that never has been called.
{
provide: 'REPOSITORY',
useValue: Repository,
},
useValue is suitable for shared values like config objects, connection strings, etc as the name imply.
If you want to inject class instance you need to configure your provider like this
{
provide: 'REPOSITORY',
useClass: Repository, // <-- notice useClass
},

Nest JS application is not starting with TypeORM 0.3 Datasource method TypeORM (0.3.10)

I have a Nest JS application using TypeORM 0.3 version. The application is not starting with the new DataSource configuration.
Error: Nest JS application is not starting with Data source new typeORM 0.3 way.
ERROR MESSAGE:
Blocked in below error. Not sure how to fix it.
Nest can't resolve dependencies of the TypeOrmModuleOptions (?). Please make sure that the argument dependency at index [0] is available in the TypeOrmCoreModule context.
Potential solutions:
If dependency is a provider, is it part of the current TypeOrmCoreModule?
If dependency is exported from a separate #Module, is that module imported within TypeOrmCoreModule?
Code:
src/db/data-source.ts
This contains TypeORM 0.3 Data source connection file
```
import {
TypeOrmModuleAsyncOptions,
TypeOrmModuleOptions,
} from '#nestjs/typeorm';
// import { Tag } from '#app/tag/tag.entity';
import { DataSource, DataSourceOptions } from 'typeorm';
export const dataSourceOptions: DataSourceOptions = {
migrationsTableName: 'migrations',
type: 'postgres',
host: process.env.HOST,
port: +process.env.PORT,
username: process.env.USERNAME,
password: process.env.PASSWORD,
database: process.env.DATABASE,
migrations: [__dirname + '\\migrations\\**\\*{.ts,.js}'],
// entities: [Tag],
// entities: [__dirname + '/**/*.entity{.ts,.js}'],
// migrations: [__dirname + '/../database/migrations/*{.ts,.js}'],
// cli: {
// migrationsDir: __dirname + '/../database/migrations',
// },
// extra: {
// charset: 'utf8mb4_unicode_ci',
// },
logging: true,
synchronize: false,
};
const dataSource = new DataSource(dataSourceOptions);
export default dataSource;
```
In Nest JS App module file imported Data source and added to imports as suggested in official documentation
Any help will be appreciated team.
Screenshots: Code and Error
Code: commit
src/app.module.ts
```
import { forwardRef, Module } from '#nestjs/common';
import { dataSourceOptions } from '#app/db/data-source';
import { AppController } from '#app/app.controller';
import { AppService } from '#app/app.service';
import { TagModule } from '#app/tag/tag.module';
import { TypeOrmModule } from '#nestjs/typeorm';
import { ConfigModule, ConfigService } from '#nestjs/config';
// import { Tag } from './tag/tag.entity';
#Module({
imports: [
ConfigModule.forRoot({ isGlobal: true }),
TypeOrmModule.forRootAsync(dataSourceOptions),
// forwardRef(() => TagModule),
// TagModule,
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
```

#nestjs/typeorm How to get current connection with v0.3.0 of typeorm in a custom decorator?

I used to have:
import { getManager } from "typeorm";
return getManager()
.count(entity, {
...where,
})
.then((count) => count < 1);
to use the current connection in a validation decorator and access to database.
But now with the version 0.3.0 of typeorm, getManager() is deprecated and I get the following error:
`ConnectionNotFoundError: Connection default was not found`
How should I use the new DataSource API to get the current connection using Nest.js in external scripts like validation decorators?
I have dealt with the following error with "typeorm": "0.3.6", before, so hopes that my experience will be relevant for you.
Instead of using getManager I am using entityManager but result is the same.
Here is the example for your case:
test.module.ts
#Module({
imports: [
TypeOrmModule.forRoot(postgresConfig), // <- connection configs
TypeOrmModule.forFeature([
TestEntity,
]),
],
controllers: [],
providers: [TestService],
})
export class TestModule {}
test.service.ts
#Injectable()
export class TestService implements OnApplicationBootstrap {
constructor(
#InjectEntityManager()
private readonly entityManager: EntityManager,
)
async onApplicationBootstrap(): Promise<void> {
const count = await this.entityManager.getRepository(TestEntity).count('query');
console.log(count);
}
}
You should also have created a typeorm entities for that.
If we are talking about migrations you could use an ormconfig.json, but also there was a problem with using typeorm combined with test frameworks like Jest and if you case is relevant with it, just mention it, and I'll find an example in on of my projects.
It should be something relevant with creating manual connections without decorator like:
export const getDatabaseConnectionOptions = (config): PostgresConnectionOptions => {
return {
type: 'postgres',
logging: config.db.logging,
connectTimeoutMS: config.db.master.connectionTimeoutMillis,
uuidExtension: 'uuid-ossp',
extra: {
idleTimeoutMillis: config.db.master.idleTimeoutMillis,
max: config.db.master.max,
keepalives_idle: config.db.master.keepalives_idle,
},
entities: process.env.TS_NODE
? [path.join(process.cwd(), 'src/**/*.entity.ts')]
: [path.join(process.cwd(), 'dist/**/*.entity.js')],
migrations: process.env.TS_NODE ? ['src/typeorm_migrations/*.ts'] : ['dist/typeorm_migrations/*.js'],
migrationsTableName: 'typeorm_migrations',
namingStrategy: new DatabaseNamingStrategy(),
replication: {
master: {
host: config.db.master.host,
port: config.db.master.port,
username: config.db.master.user,
password: config.db.master.password,
database: config.db.master.database,
},
slaves: [
{
host: config.db.slave.host,
port: config.db.slave.port,
username: config.db.slave.user,
password: config.db.slave.password,
database: config.db.slave.database,
},
],
},
cli: {
migrationsDir: 'src/typeorm_migrations',
},
};
};
export const createDatabaseConnection = async (config): Promise<Connection> => {
// Setup TypeDI
useContainer(Container);
// Setup typeorm-transactional-cls-hooked
initializeTransactionalContext();
patchTypeORMRepositoryWithBaseRepository();
return await createConnection(config);
};
const connection = await createDatabaseConnection(getDatabaseConnectionOptions(config));
const { app } = createAppApi();
and then access to managers or entities via connection props.

NestJS -- JWT Dependency is not being loaded

I do not need complete passport, I just need to sign a JWT token.
I tried working with this repository
I tried all possible combinations, but I just cant integrate it in the project. I had followed the course of several different errors. I fix one, and the another pops up. So, I am including minimum part, and the current error that is thrown.
AuthModule:
import { Module } from '#nestjs/common';
import { JwtModule } from '#nestjs/jwt';
import { AuthService } from './auth.service';
import { JwtService } from '#nestjs/jwt';
#Module({
imports: [ JwtModule.register({ secret: 'hard!to-guess_secret' })],
providers: [AuthService],
exports: [AuthService, JwtService]
})
export class AuthModule {}
AuthService:
import { Injectable } from '#nestjs/common';
import { UsersService } from '../users/users.service';
import { JwtService } from '#nestjs/jwt';
#Injectable()
export class AuthService {
constructor(
private readonly jwtService: JwtService,
) {}
async signPayload (user: any) {
const payload = { username: 'HARDCORE', color:'RED' };
return {
whatever: this.jwtService.sign(payload),
};
}
}
AppModule:
#Module({
imports: [
ConfigModule.forRoot(),
JwtModule.registerAsync({
imports: [ConfigModule],
useFactory: async (configService: ConfigService) => ({
secret: 'wefwefwef',
}),
inject: [ConfigService],
}),
TypeOrmModule.forRoot({
type: 'mysql',
...
}),
UsersModule,
SubscriptionsModule,
ProductsModule
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {
}
SomeController:
export class UsersController {
constructor(private readonly usersService: UsersService,
private readonly authService: AuthService
) {}
...
#ApiResponse({ status: 401, description: 'Unauthorized.' })
#ApiResponse({ status: 404, description: 'User Not Found.' })
#Get('users')
async findOne(#Query() userGetDto: UserGetDto): Promise<User> {
const user = await this.usersService.findByUsername(userGetDto.userName);
if (!user) throw new NotFoundException('User Not Found')
let signedUser = this.authService.signPayload(user);
return user;
And this is the error with this setup that I get:
Nest can't resolve dependencies of the JwtService (?). Please make
sure that the argument JWT_MODULE_OPTIONS at index [0] is available in
the JwtService context.
I spend lot of time on this one, but I just cant make it work.
Based on your error, JwtService is in an imports array somewhere. Providers (classes marked with #Injectable()) never go in the imports array, but rather should be added to the exports array and that module where the exports was added should be put in the consuming module's imports array.
Also, if you are working with a Dynamic Module (any module that uses register or forRoot or an async variant of the two) you should always export the module instead of its services, as the module most likely has important configurations necessary for the service to work.

NestJS/TypeORM - connecting to multiple databases - ConnectionNotFoundError

Connecting to two databases using TypeORM and NestJS throws a ConnectionNotFoundError when a custom repository is registered using the connection (UserConnection & PhotoConnection) one for each database. I have created a minimal repo here https://github.com/masonridge/connissuewithndb. The TypeOrm registration is done in the AppModule of NestJS
(app.module.ts)
#Module({
imports: [
TypeOrmModule.forRootAsync({
name: 'PhotoConnection',
useFactory: async () => {
return {
type: 'sqlite',
synchronize: true,
database: 'TestPhoto.sqlite',
entities: [Photo],
} as SqliteConnectionOptions;
},
}),
TypeOrmModule.forRootAsync({
name: 'UserConnection',
useFactory: async () => {
return {
type: 'sqlite',
synchronize: true,
database: 'TestUser.sqlite',
entities: [User],
} as SqliteConnectionOptions;
},
}),
// TypeOrmModule.forFeature([User, UserRepository], 'UserConnection'),
// TypeOrmModule.forFeature([Photo, PhotoRepository], 'PhotoConnection'),
PhotoModule, UserModule,
],
(photo.module.ts) DB connection1 - PhotoConnection is registered here
#Module({
imports: [
TypeOrmModule.forFeature([PhotoRepository], 'PhotoConnection'),
],
providers: [
PhotoService,
],
controllers: [PhotoController],
exports: [TypeOrmModule],
})
export class PhotoModule {}
(user.module.ts) DB connection2 - UserConnection is registered here
#Module({
imports: [
TypeOrmModule.forFeature([UserRepository], 'UserConnection'),
],
providers: [
UserService,
],
exports: [TypeOrmModule],
controllers: [UserController],
})
export class UserModule {}
(user.repository.ts) Custom repository
#EntityRepository(User)
export class UserRepository extends Repository<User> {
async createUser(name: string): Promise<string> {
const user = this.create();
user.username = name;
user.salt = 'salt';
user.password = 'xxkdkdk';
user.save();
return name;
}
}
(photo.repository.ts)
#EntityRepository(Photo)
export class PhotoRepository extends Repository<Photo> {
async createPhoto(name: string): Promise<string> {
const photo = this.create();
photo.name = name;
photo.save();
return name;
}
}
The repo is injected into the service using the connection (PhotoConnection)
(photo.service.ts)
export class PhotoService {
constructor(
#InjectRepository(Photo, 'PhotoConnection')
private readonly photoRepository: PhotoRepository,
) {}
and here using UserConnection (user.service.ts)
#Injectable()
export class UserService {
constructor(
#InjectRepository(User, 'UserConnection')
private readonly userRepository: UserRepository,
) {}
The application starts fine but on a POST request it throws a ConnectionNotFoundError error
(node:190812) UnhandledPromiseRejectionWarning: ConnectionNotFoundError: Connection "default" was not found.
at new ConnectionNotFoundError (C:\nestjs\type-orm-dbscratch\node_modules\typeorm\error\ConnectionNotFoundError.js:10:28)
at ConnectionManager.get (C:\nestjs\type-orm-dbscratch\node_modules\typeorm\connection\ConnectionManager.js:38:19)
at Object.getConnection (C:\nestjs\type-orm-dbscratch\node_modules\typeorm\index.js:244:35)
at Function.BaseEntity.getRepository (C:\nestjs\type-orm-dbscratch\node_modules\typeorm\repository\BaseEntity.js:67:57)
at Photo.BaseEntity.save (C:\nestjs\type-orm-dbscratch\node_modules\typeorm\repository\BaseEntity.js:27:33)
at PhotoRepository.createPhoto (C:\nestjs\type-orm-dbscratch\dist\db\photo\photo.repository.js:15:15)
at PhotoService.createPhoto (C:\nestjs\type-orm-dbscratch\dist\db\photo\photo.service.js:24:43)
at PhotoController.addSetting (C:\nestjs\type-orm-dbscratch\dist\db\photo\photo.controller.js:22:27)
at C:\nestjs\type-orm-dbscratch\node_modules#nestjs\core\router\router-execution-context.js:37:29
at process._tickCallback (internal/process/next_tick.js:68:7)
I would like to know if there is an issue with the registration. Any help would be appreciated.
It looks like the issue is between using the TypeORM approach of DataMapper and ActiveRecord. It seems using the ActiveRecord approach does not support named repositories with NestJS, and as such was looking for connection named 'default'. If you remove the extends BaseEntity and use the repository's save method instead this.save(user) vs user.save() you'll get a successful save. I didn't see an immediate way to set the connection of the ActiveRecord but it may be an option somewhere if that is still the approach you would like to follow.

Resources