Why lazyload is not working on submodules? - angular-ui-router

I have a little question , i try to customize my router for lazy load Angular CLI 8 , if i try to put loadChildren on sub modules i have some errors.
app.routing.ts
import { CommonModule, } from '#angular/common';
import { BrowserModule } from '#angular/platform-browser';
import { Routes, RouterModule } from '#angular/router';
import { LoginComponent } from './login/login.component';
import {CoreComponent} from './core/core.component';
const routes: Routes = [
{
path: '',
redirectTo: 'dashboard',
pathMatch: 'full',
},
{
path: 'login',
component: LoginComponent
},
{
path: '',
component: CoreComponent,
children: [
{
path: '',
loadChildren: () => import('./core/core.module').then(mod => mod.CoreModule)
}
]
}
];
#NgModule({
imports: [
CommonModule,
BrowserModule,
RouterModule.forRoot(routes , {
enableTracing: false
})
],
exports: [
RouterModule
],
})
export class AppRoutingModule { }
on core.module.ts -> This is working
import { RouterModule } from '#angular/router';
import { CommonModule } from '#angular/common';
import { CoreRoutes } from '../_config/route';
import { TableListComponent } from '../table-list/table-list.component';
import { TypographyComponent } from '../typography/typography.component';
import { IconsComponent } from '../icons/icons.component';
import { MapsComponent } from '../maps/maps.component';
import { NotificationsComponent } from '../notifications/notifications.component';
import { UpgradeComponent } from '../upgrade/upgrade.component';
import {UsersComponent} from '../users/user-list/users.component';
import {UserDetailsComponent} from '../users/user-details/user-details.component';
#NgModule({
imports: [
CommonModule,
RouterModule.forChild(CoreRoutes)
],
declarations: [
TableListComponent,
TypographyComponent,
IconsComponent,
MapsComponent,
NotificationsComponent,
UpgradeComponent,
UsersComponent,
UserDetailsComponent
],
providers : [
]
})
export class CoreModule {}
on route.ts - > in this case loadchildren only works if i include full path like this '../dashboard/dashboard.module#DashboardModule'
import { AuthGuard } from '../_helpers';
import {SandboxComponent, UsersComponent} from '../users/user-list/users.component';
import {UserDetailsComponent} from '../users/user-details/user-details.component';
export const CoreRoutes: Routes = [
{
path: 'dashboard',
loadChildren: () => import('../dashboard/dashboard.module').then(mod => mod.DashboardModule),
// '../dashboard/dashboard.module#DashboardModule'
canActivate: [AuthGuard],
},
{
path: 'users',
component: UsersComponent,
children: [
{ path: 'sandbox', component: SandboxComponent } // url: about/item
]
},
{
path: 'users/sandbox',
component: UsersComponent
},
{ path: 'user/:id', component: UserDetailsComponent }
];
ERROR in src\app\core\core.module.ts(18,31): Error during template compile of 'CoreModule'
Function expressions are not supported in decorators in 'CoreRoutes'
'CoreRoutes' contains the error at src\app\_config\route.ts(8,23)
Consider changing the function expression into an exported function.```

I find the problem with this.
The problem was when i started the server with --aot (Ahead Of Time) parameter and CLI version is 7.X , if i run simple like ng serve everything works (JIT - Just in time) compiler.
According there documents https://angular.io/guide/aot-compiler this is coming from 6 CLI version and something happens after update CLI to 7 / 8

Related

Unexpected type error in websockets when compiling nest js project

Below is my code
I tried to set a web socket gateway as below.
events.gateways.ts
import {
MessageBody,
SubscribeMessage,
WebSocketGateway,
WebSocketServer,
} from "#nestjs/websockets";
import { Server } from "socket.io";
#WebSocketGateway({
cors: {
origin: "http://localhost:3000",
},
})
export class EventsGateway {
#WebSocketServer()
server: Server;
#SubscribeMessage("events")
handleEvent(#MessageBody() data: string): string {
return data;
}
}
I set above gateway as a provider to a module.
events.module.ts
import { Module } from "#nestjs/common";
import { EventsGateway } from "./events.gateway";
#Module({
providers: [EventsGateway],
})
export class EventsModule {}
Fianllt, i imported above module to the app.module.ts and now I am getting the error
app.module.ts
import { Module } from "#nestjs/common";
import { AppController } from "./app.controller";
import { AppService } from "./app.service";
import { APP_FILTER } from "#nestjs/core";
import { AllExceptionFilter } from "./all-exception.filter";
import { ConfigModule } from "#nestjs/config";
import { TypeOrmModule } from "#nestjs/typeorm";
import { Student } from "./student/entities/student.entity";
import { EventsModule } from "./events/events.module";
#Module({
imports: [
ConfigModule.forRoot(),
TypeOrmModule.forRoot({
type: "postgres",
host: process.env.DB_HOST,
port: parseInt(process.env.DB_PORT as string) | 5432,
username: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD,
database: process.env.DB_DATABASE,
entities: [Student],
synchronize: true,
}),
EventsModule,
],
controllers: [AppController],
providers: [
{
provide: APP_FILTER,
useClass: AllExceptionFilter,
},
AppService,
],
})
export class AppModule {}
This is the error I am keep getting.
TypeError: this.graphInspector.insertEntrypointDefinition is not a function
at /home/Desktop/New Folder/nest_try_1/node_modules/#nestjs/websockets/web-sockets-controller.js:108:33
at Array.forEach (<anonymous>)
at WebSocketsController.inspectEntrypointDefinitions (/home/Desktop/New Folder/nest_try_1/node_modules/#nestjs/websockets/web-sockets-controller.js:106:25)
at WebSocketsController.subscribeToServerEvents (/home/Desktop/New Folder/nest_try_1/node_modules/#nestjs/websockets/web-sockets-controller.js:39:14)
at WebSocketsController.connectGatewayToServer (/home/Desktop/New Folder/nest_try_1/node_modules/#nestjs/websockets/web-sockets-controller.js:30:14)
at SocketModule.connectGatewayToServer (/home/Desktop/New Folder/nest_try_1/node_modules/#nestjs/websockets/socket-module.js:47:35)
at /home/Desktop/New Folder/nest_try_1/node_modules/#nestjs/websockets/socket-module.js:36:38
at IteratorWithOperators.forEach (/home/Desktop/New Folder/nest_try_1/node_modules/iterare/lib/iterate.js:157:13)
at SocketModule.connectAllGateways (/home/Desktop/New Folder/nest_try_1/node_modules/#nestjs/websockets/socket-module.js:36:14)
at /home/Desktop/New Folder/nest_try_1/node_modules/#nestjs/websockets/socket-module.js:31:61
Node.js v19.4.0
I am follwing the documentation and I am keep getting above error.
you should align your dependencies, ie., if you're using #nestjs/websockets v9.3.1, #nestjs/core must be in v9.3.1 as well
Run npx nest info and check that out.
That error is because #nestjs/websockets is invoking a method added in v9.3 which depends on a method added in v9.3 of #nestjs/core as well.
btw there are closed issues on GitHub about that error: https://github.com/nestjs/nest/issues?q=is%3Aissue+sort%3Aupdated-desc+is%3Aclosed+insertEntrypointDefinition

Confused about AngularFire Functions modules and imports

I spun up a new project with Angular and AngularFire. I ran
firebase init firestore
firebase init functions
This set up this Angular module:
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { AppComponent } from './app.component';
import { initializeApp,provideFirebaseApp } from '#angular/fire/app';
import { environment } from '../environments/environment';
import { provideFirestore,getFirestore } from '#angular/fire/firestore';
import { provideFunctions,getFunctions } from '#angular/fire/functions';
#NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
provideFirebaseApp(() => initializeApp(environment.firebase)),
provideFirestore(() => getFirestore()),
provideFunctions(() => getFunctions())
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
I didn't write any of that. It looks like AngularFire 7.
The AngularFire Functions documentation shows a different module setup. It looks like AngularFire 6:
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { AppComponent } from './app.component';
import { AngularFireModule } from '#angular/fire/compat';
import { AngularFireFunctionsModule } from '#angular/fire/compat/functions';
import { environment } from '../environments/environment';
#NgModule({
imports: [
BrowserModule,
AngularFireModule.initializeApp(environment.firebase),
AngularFireFunctionsModule
],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule {}
The differences are that the new module has:
import { initializeApp,provideFirebaseApp } from '#angular/fire/app';
import { provideFirestore,getFirestore } from '#angular/fire/firestore';
import { provideFunctions,getFunctions } from '#angular/fire/functions';
...
provideFirebaseApp(() => initializeApp(environment.firebase)),
provideFirestore(() => getFirestore()),
provideFunctions(() => getFunctions())
There are two extra lines because I initialized Firestore. The older module has this:
import { AngularFireModule } from '#angular/fire/compat';
import { AngularFireFunctionsModule } from '#angular/fire/compat/functions';
...
AngularFireModule.initializeApp(environment.firebase),
AngularFireFunctionsModule
I left the new module as is and went on to the component. Here's what the AngularFire Functions documentation says to use this (I added a template and stylesheet):
import { Component } from '#angular/core';
import { AngularFireFunctions } from '#angular/fire/compat/functions';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private functions: AngularFireFunctions) { }
}
That component throws an error message:
R3InjectorError(AppModule)[AngularFireFunctions -> InjectionToken
It can't inject AngularFireFunctions.
I went back to the module and added these lines:
import { AngularFireFunctionsModule } from '#angular/fire/compat/functions';
...
imports: [
...
AngularFireFunctionsModule
],
That doesn't fix the error. The error only goes away when I add this code to the module:
import { AngularFireModule } from '#angular/fire/compat';
import { AngularFireFunctionsModule } from '#angular/fire/compat/functions';
...
imports: [
BrowserModule,
// provideFirebaseApp(() => initializeApp(environment.firebase)),
provideFirestore(() => getFirestore()),
provideFunctions(() => getFunctions()),
AngularFireModule.initializeApp(environment.firebase),
AngularFireFunctionsModule
],
In other words, I commented out the AngularFire 7 version of initializeApp and used the AngularFire 6 version of initializeApp.
This code is getting smelly. It seems to me that I should leave the module alone and in the component I should import httpsCallable and AngularFireFunctions from #angular/fire/functions. No problem importing httpsCallable but AngularFireFunctions isn't on #angular/fire/functions.
I feel like the component should look like this:
import { Component } from '#angular/core';
import { Firestore, doc, getDoc, getDocs, collection, updateDoc } from '#angular/fire/firestore';
import { httpsCallable, AngularFireFunctions } from '#angular/fire/functions';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private functions: AngularFireFunctions) {}
callMe() {
console.log("Calling...");
this.functions.httpsCallable('helloWorld');
}
}
The problem is in AngularFireFunctions. Has this been replaced with something new in AngularFire 7?
I looked through the AngularFire repo on GitHub looking for #angular/fire/functions but I couldn't find this. Where can I see the properties on this type?
There's no AngularFire 7 module for Functions. Use the Firebase module:
import { getFunctions, httpsCallable, httpsCallableFromURL } from "firebase/functions";

When I run nest.js, I get a Missing "driver" option error

I am using nest.js, prisma, and graphql.
When I run the npm run start:dev command, I get an error.
If anyone knows how to solve this, please let me know.
ERROR [GraphQLModule] Missing
"driver" option. In the latest version of "#nestjs/graphql" package
(v10) a new required configuration property called "driver" has been
introduced. Check out the official documentation for more details on
how to migrate (https://docs.nestjs.com/graphql/migration-guide).
Example:
GraphQLModule.forRoot({
driver: ApolloDriver,
})
app.module.ts
import { Module } from '#nestjs/common';
import { GraphQLModule } from '#nestjs/graphql';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { ApolloServerPluginLandingPageLocalDefault } from 'apollo-server-core';
import { DonationsModule } from './donations/donations.module';
#Module({
imports: [
GraphQLModule.forRoot({
playground: false,
plugins: [ApolloServerPluginLandingPageLocalDefault()],
typePaths: ['./**/*.graphql'],
}),
DonationsModule,
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
generate-typings.ts
import { GraphQLDefinitionsFactory } from '#nestjs/graphql';
import { join } from 'path';
const definitionsFactory = new GraphQLDefinitionsFactory();
definitionsFactory.generate({
typePaths: ['./src/**/*.graphql'],
path: join(process.cwd(), 'src/graphql.ts'),
outputAs: 'class',
watch: true,
});
fix
#Module({
imports: [
GraphQLModule.forRoot<ApolloDriverConfig>({
driver: ApolloDriver,
autoSchemaFile: true,
plugins: [ApolloServerPluginLandingPageLocalDefault()],
typePaths: ['./**/*.graphql'],
}),
DonationsModule,
],
controllers: [AppController],
providers: [AppService],
})
Checkout the nestjs/graphql documentation page and the other link that you have mentioned. You have to configure your GraphQLModule like this which I don't see in your code.
#Module({
imports: [
GraphQLModule.forRoot<ApolloDriverConfig>({
driver: ApolloDriver,
}),
],
})
Also don't forget to import
import { ApolloDriverConfig, ApolloDriver } from '#nestjs/apollo';

document is not defined when do "tns test android"

I create a login.component.spec.ts for my loginComponent. However, when I run tns test android, the TestBed.createComponent(LoginComponent) failed. The error is below:
NativeScript / 29 (10; Android SDK built for x86) LoginComponent
Should create the app FAILED
Failed: StaticInjectorError(DynamicTestModule)[TestComponentRenderer
-> InjectionToken DocumentToken]:
StaticInjectorError(Platform: core)[TestComponentRenderer ->
InjectionToken DocumentToken]: document is not defined
error properties: Object({ ngTempTokenPath: null, ngTokenPath: [
'TestComponentRenderer', InjectionToken DocumentToken ] }) at Jasmine
I cannot find any result in website about my problem. Thanks for helping.
I tried to include http module since someone said the undefined document may because of http. However, it still does not work.
This is code for login.component.spec.ts:
import "core-js";
import "zone.js/dist/zone";
import "zone.js/dist/proxy";
import "zone.js/dist/sync-test";
import "zone.js/dist/async-test";
import "zone.js/dist/fake-async-test";
import "zone.js/dist/jasmine-patch";
import "zone.js/dist/long-stack-trace-zone";
import { ComponentFixture, async, TestBed} from '#angular/core/testing';
import { By } from '#angular/platform-browser';
import { NO_ERRORS_SCHEMA, DebugElement} from '#angular/core';
import { RouterTestingModule } from '#angular/router/testing';
import { Router } from '#angular/router';
import { ActivatedRoute } from "#angular/router";
import { RouterExtensions } from "nativescript-angular/router";
import { BrowserDynamicTestingModule, platformBrowserDynamicTesting }
from '#angular/platform-browser-dynamic/testing';
import { LoginComponent } from '~/pages/login/login.component';
describe ('LoginComponent', () => {
beforeEach(async( () => {
TestBed.resetTestEnvironment();
TestBed.initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting());
TestBed.configureTestingModule({
imports: [
RouterTestingModule
],
providers: [],
declarations: [
LoginComponent
],
schemas: [
NO_ERRORS_SCHEMA]
}).compileComponents();
}));
it('Should create the app', async( () => {
const fixture = TestBed.createComponent(LoginComponent);
const app = fixture.debugElement.componentInstance;
expect(app).toBeTruthy();
}));
});
You are using the BrowserDynamicTestingModule which is not valid for {N}. You are suppose to use NativeScriptTestingModule form nativescript-angular/testing.

Angular 2 Component routing

I am planning to start learning angular 2 component router.
I have used Angular ui-router heavily.All my projects uses UI-router complex features like nested states and nested named views.
What will be good start to use angular 2 component router?
how can I configure nested states in Angular 2 component router?
All in all i would say routing is pretty simple and intuitive in angular 2
I would suggest reading through the router docs to get all the basics.
Keep in mind that child components can have routes too. They build from its parents routes.
app.component.ts (excerpt)
#Component({ ... })
#RouteConfig([
{path:'/crisis-center/...', name: 'CrisisCenter', component: CrisisListComponent},
{path:'/heroes', name: 'Heroes', component: HeroListComponent},
{path:'/hero/:id', name: 'HeroDetail', component: HeroDetailComponent}
])
export class AppComponent { }
crisis-center.component.ts(excerpt)
#RouteConfig([
{path:'/', name: 'CrisisCenter', component: CrisisListComponent, useAsDefault: true},
{path:'/:id', name: 'CrisisDetail', component: CrisisDetailComponent}
])
Notice that the path ends with a slash and three trailing periods (/...).
That means this is an incomplete route (AKA a non-terminal route). The finished route will be some combination of the parent /crisis-center/ route and a route from the child router that belongs to the designated component.
All is well. The parent route's designated component is the CrisisCenterComponent which is a Routing Component with its own router and routes.
From angular.io router guide
You can define a app.routing.ts like below.
export const routes: Routes = [
{
path: '',
component: SimpleLayoutComponent,
data: {
title: 'Login form'
},
children: [
{
path: '', component: LoginComponent,
}
]
},
{
path: 'dashboard',
component: FullLayoutComponent,
data: {
title: 'Home'
},
children: [
{
path: '',
component: 'mycomponent'
}
]
}
];
Then import this class to your app.module.ts file like below.
import { AppRoutingModule } from './app.routing';
#NgModule({
imports: [
BrowserModule,
HttpModule,
FormsModule,
AppRoutingModule,
],
declarations: [
AppComponent,
LoginComponent
],
providers: [
UserService, AuthGuard],
bootstrap: [ AppComponent ]
})
export class AppModule { }
app.component.ts Below: views get injected in
import { Component } from '#angular/core';
#Component({
selector: 'body',
template: '<router-outlet></router-outlet>'
})
export class AppComponent { }
#NgModule({
declarations: [AppComponent,CreateComponent,ListComponent],
imports: [
BrowserModule,
FormsModule,
ReactiveFormsModule,
HttpModule,
RouterModule.forRoot([
{path:"",component:ListComponent},
{path:"Create",component:CreateComponent},
])
],
bootstrap: [AppComponent]
})
Put this RouterModule in app.module file.
For this you have to import { RouterModule} ;
<router-outlet></router-outlet>
Put router-outlet element in app.component.html to render component through routing.

Resources