Nativescript - Error: Type AppRoutingModule does not have 'ngModuleDef' property - nativescript-angular

I want to get my hands on Nativescript + Angular using quick preview but I am getting an error while running the tns preview command. I don't want to go through the full setup of nativescript. I am Angular v11 installed on my machine.
Error: Type AppRoutingModule does not have 'ngModuleDef' property.
at com.tns.Runtime.runModule(Native Method)
at com.tns.Runtime.runModule(Runtime.java:674)
at com.tns.Runtime.run(Runtime.java:666)
at com.tns.NativeScriptApplication.onCreate(NativeScriptApplication.java:21)
at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1165)
at android.app.ActivityThread.handleBindApplication(ActivityThread.java:6039)
at android.app.ActivityThread.access$1300(ActivityThread.java:207)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1748)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6863)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:537)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Is there any workaround to launch the preview without downgrading angular version?
import { NgModule } from "#angular/core";
import { Routes } from "#angular/router";
import { NativeScriptRouterModule } from "#nativescript/angular";
const routes: Routes = [
{ path: "", redirectTo: "/home", pathMatch: "full" },
{ path: "home", loadChildren: () => import("~/app/home/home.module").then((m) => m.HomeModule) },
{ path: "browse", loadChildren: () => import("~/app/browse/browse.module").then((m) => m.BrowseModule) },
{ path: "search", loadChildren: () => import("~/app/search/search.module").then((m) => m.SearchModule) },
{ path: "featured", loadChildren: () => import("~/app/featured/featured.module").then((m) => m.FeaturedModule) },
{ path: "settings", loadChildren: () => import("~/app/settings/settings.module").then((m) => m.SettingsModule) }
];
#NgModule({
imports: [NativeScriptRouterModule.forRoot(routes)],
exports: [NativeScriptRouterModule]
})
export class AppRoutingModule { }

Related

firebase authentication freezing edge and chrome browser

so just new with angular and firebase, i am trying to create authentication, the code is not throwing any error but when i try accessing it in the browser it freezes, i can't even click on anything. below are the authentication code.
import { Injectable, NgZone } from '#angular/core';
import { AngularFireAuth } from '#angular/fire/compat/auth';
import { AngularFirestore, AngularFirestoreDocument } from '#angular/fire/compat/firestore';
import { Router } from '#angular/router';
import * as auth from 'firebase/auth';
import { UserService } from '../users/user.service';
//import { User } from '../../models/users/user';
import { DataService } from '../database/data.service';
#Injectable({
providedIn: 'root'
})
export class AuthService {
loggedin = false;
// user$: Observable<any> | undefined;
// user: any;
userData: any;
constructor(
public firestore: AngularFirestore,
public fireauth: AngularFireAuth,
public userservice: UserService,
public router: Router,
public ngZone: NgZone,
public dataService: DataService,
) {
// this.fireauth.authState.subscribe((user) => {
// if (user){
// this.userData = user;
// this.dataService.addData('users', this.userData); // you can json stringify this if you want
// localStorage.setItem('user', JSON.stringify(this.userData));
// JSON.parse(localStorage.getItem('user') || '{}');
// }
// else {
// this.dataService.addData('users', null);
// localStorage.setItem('user', '');
// JSON.parse(localStorage.getItem('user') || '{}');
// }
// });
//this.loggedin = !!localStorage.getItem('user');
}
// Sign in with email/password
async loginUser(email: string, password: string) {
try {
const result = await this.fireauth
.signInWithEmailAndPassword(email, password);
this.SetUserData(result.user);
this.fireauth.authState.subscribe((user_1) => {
if (user_1) {
this.router.navigate(['dashboard']);
}
});
} catch (error) {
window.alert(error);
}
}
i have comment out eveery code int he login components but i still get this issue,
app.modules
#NgModule({
declarations: [
AppComponent,
LoginComponent,
OrderListComponent,
DashboardComponent,
ProfileGeneralComponent,
MenuComponent,
ProfileMenuComponent,
ProfileServicesComponent,
Dashboard2Component,
LineChartComponent,
],
imports: [
BrowserModule,
RouterModule,
FormsModule,
ReactiveFormsModule,
AppRoutingModule,
IonicStorageModule.forRoot(),
IonicModule.forRoot({
mode: 'ios'
}),
AngularFireModule.initializeApp(environment.firebase),
AngularFireAuthModule,
AngularFirestoreModule,
AngularFireStorageModule,
AngularFireDatabaseModule,
provideFirebaseApp(() => initializeApp(environment.firebase)),
provideAuth(() => getAuth()),
provideFirestore(() => getFirestore()),
provideStorage(() => getStorage()),
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
app-routing.module
const routes: Routes = [
{ path: '', component: LoginComponent },
{
path: 'dashboard',
//canActivate: [AuthGuard],
component: DashboardComponent
},
{
path: 'overview-dashboard',
canActivate: [AuthGuard],
component: Dashboard2Component
},
{
path: 'profile',
canActivate: [AuthGuard],
component: ProfileGeneralComponent
},
{
path: 'profile-menu',
canActivate: [AuthGuard],
component: ProfileMenuComponent
},
{
path: 'profile-services',
canActivate: [AuthGuard],
component: ProfileServicesComponent
},
{
path: 'order-list',
canActivate: [AuthGuard],
component: OrderListComponent
},
{
path: 'login',
canActivate: [AuthGuard],
component: LoginComponent
},
{
path: 'line-chart',
canActivate: [AuthGuard],
component: LineChartComponent
}
];
#NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
when i access other pages with nothing related to authentication they work.

NestJS - gRPC Client E2E Test

I am trying to write an e2e test for my NestJS microservice that has a gRPC client. No matter what I do to try and mock the ClientsModule in the e2e test it still seems to not pick up the config and is unable to locate the *.proto file.
Please find a sample of my code below:
The clients module in the app.module.ts
// src/app.module.ts
#Module({
imports: [
HttpModule,
...
...
ClientsModule.register([
{
name: 'USERS_PACKAGE',
transport: Transport.GRPC,
options: {
package: 'users',
credentials: credentials.createInsecure(),
protoPath: join(__dirname, '../proto/users.proto'),
url: 'users-grpc-server.users:50051',
},
},
]),
],
controllers: [UsersController],
providers: [UsersService, UsersClient],
})
export class AppModule {}
The users client to make the gRPC call to the gRPC Server NestJS microservice:
// src/clients/users.client.ts
#Injectable()
export class UsersClient implements OnModuleInit {
private readonly logger: Logger = new Logger(UsersClient.name);
private readonly API_KEY: string = this.configService.get<string>('services.v1.api-key');
private usersController: usersController;
constructor(#Inject('USERS_PACKAGE') private client: ClientGrpc, private configService: ConfigService) {}
onModuleInit() {
this.usersController = this.client.getService<UsersController>('UsersController');
}
async getUsers(headers: IncomingHttpHeaders, userId: string): Promise<Users> {
let users: Users = null;
const metadata = new Metadata();
metadata.add('Authorization', headers.authorization);
metadata.add('x-api-key', this.API_KEY);
try {
users = await this.usersController.getUsers({}, metadata);
} catch (e) {
const { message, response: { status = 500 } = {}, stack } = e;
this.logger.error(stack);
throw new HttpException(message, status);
}
return users;
}
}
The update nest-cli.json
{
"collection": "#nestjs/schematics",
"sourceRoot": "src",
"compilerOptions": {
"assets": [{"include": "../config/*.yaml", "outDir": "./dist/config"}, {"include": "**/*.proto", "outDir": "./dist"}]
}
}
The e2e test configuration
// test/app.e2e-spec.json
let app: NestFastifyApplication;
let httpService: HttpService;
let cacheManager: Cache;
beforeAll(async () => {
const module: TestingModule = await Test.createTestingModule({
imports: [
HttpModule,
...
...
ClientsModule,
],
})
.overrideProvider(ClientsModule)
.useValue({
name: 'USERS_PACKAGE',
transport: Transport.GRPC,
options: {
package: 'users',
credentials: ServerCredentials.createInsecure(),
protoPath: join(__dirname, '../src/proto/users.proto'),
url: 'localhost:50051',
},
})
.compile();
app = module.createNestApplication(new FastifyAdapter());
await app.init();
await app.getHttpAdapter().getInstance().ready();
httpService = module.get<HttpService>(HttpService);
cacheManager = module.get<Cache>(CACHE_MANAGER);
});
The error:
● Test suite failed to run
The invalid .proto definition (file at "/users-service-grpc-client/app/proto/users.proto" not found)
> 26 | ClientsModule.register([
| ^
27 | {
28 | name: 'USERS_PACKAGE',
29 | transport: Transport.GRPC,
at ClientGrpcProxy.loadProto (node_modules/#nestjs/microservices/client/client-grpc.js:220:39)
at ClientGrpcProxy.createClients (node_modules/#nestjs/microservices/client/client-grpc.js:193:34)
at new ClientGrpcProxy (node_modules/#nestjs/microservices/client/client-grpc.js:29:33)
at Function.create (node_modules/#nestjs/microservices/client/client-proxy-factory.js:27:24)
at node_modules/#nestjs/microservices/module/clients.module.js:12:80
at Array.map (<anonymous>)
at Function.register (node_modules/#nestjs/microservices/module/clients.module.js:10:41)
at Object.<anonymous> (src/app.module.ts:26:19)
It seems like the the e2e test isnt using the ClientsModule configuration from the test and is still using the ClientsModule configuration from the app.module.ts.
Does anyone know of a way to configure this correctly ?
I am not sure how this is working but I changed the ClientsModule in the src/app.module.ts to be registerAsync because I wanted to make the url dynamic and it now seems to be working correctly
// src/app.module.ts
#Module({
imports: [
HttpModule,
...
...
ClientsModule.registerAsync([
{
name: 'USERS_PACKAGE',
imports: [ConfigModule],
useFactory: async (configService: ConfigService) => ({
transport: Transport.GRPC,
options: {
package: 'users',
credentials: credentials.createInsecure(),
protoPath: join(__dirname, '../proto/users.proto'),
url: configService.get<string>('services.users-grpc-server-service.url'),
},
}),
inject: [ConfigService],
},
]),
],
controllers: [UsersController],
providers: [UsersService, UsersClient],
})
export class AppModule {}
Note: In the E2E test, I also had to mock the grpc call using overrideProvider
// test/app.e2e-spec.ts
const module: TestingModule = await Test.createTestingModule({
imports: [
HttpModule,
...
...
ClientsModule,
],
})
.overrideProvider('USERS_PACKAGE')
.useValue({
getService: () => ({
getUsers: jest.fn().mockReturnValue({
"name": "test user",
"age": "55",
"height": "1.89"
}),
}),
})
.compile();

Nestjs and nestjs-i18n: Internationalization not working in Custom Exception Filter

I am trying to use an exception filter in my NestJS app. I have to translate my exception message into another language based on the request value. I have two languages file en and fr.
I have initialized i18N in my app.module.ts as per the following:
#Module({
imports: [
I18nModule.forRoot({
fallbackLanguage: 'en',
parser: I18nJsonParser,
parserOptions: {
path: path.join(__dirname, '/i18n/'),
},
resolvers: [
PathResolver,
{ use: QueryResolver, options: ['lang', 'locale', 'l'] },
AcceptLanguageResolver
]
}),
],
controllers: [AppController],
providers: [AppService,
{
provide: APP_FILTER,
useClass: NotFoundExceptionFilter,
},
{
provide: APP_FILTER,
useClass: HttpExceptionFilter,
}
],
})
export class AppModule { }
My Exception filter class looks like this:
#Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter<HttpException> {
constructor(private readonly i18n: I18nService) { }
async catch(exception: HttpException, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse();
const request = ctx.getRequest();
const statusCode = exception.getStatus();
await this.i18n.translate('message.Unauthorized', { lang: 'fr' }).then(message => {
console.log('message -> ', message);
response.status(403).send({
status: 6,
message: message,
data: null
});
})
}
}
I am throwing an exception from the LocalAuthGuard file:
#Injectable()
export class LocalAuthGuard implements CanActivate {
canActivate(context: ExecutionContext,): boolean | Promise<boolean> | Observable<boolean> {
const request = context.switchToHttp().getRequest().body;
if(isEmpty(request.authkey)){
return false;
}else{
return true;
}
}
}
I have just put here my sample code from the project. When I run this project by some specific URL, I am not getting messages in the specific language. I am getting the following output in my console log.
message -> message.Unauthorized
It should return the message in fr language.
Can anybody help me, where am I going wrong?
I forgot to add the path in nest-cli.json. If we put the path in that file as below then the above code perfectly works fine.
{
"collection": "#nestjs/schematics",
"sourceRoot": "src",
"compilerOptions": {
"assets": ["i18n/**/*","ssl/**/*"]
}
}

How to set up my routing that "pathMatch" and childRoutingModule work?

On the left-side menu I need to have the links highlighted when the user on them. Now it works but my root path 'li' of the menu is highlighted as well.
I cannot set up a child routing Module.
left-side-menu html
<ul class='side-menu'>
<li *ngFor='let item of menu' routerLinkActive='active-side-menu-item'><a routerLink='{{ item.link }}' class="menu-item-feed">{{ item.title }}</a></li>
</ul>
app.routing.module ts
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { FeedComponent } from './feed/feed.component';
const routes: Routes = [
{ path: '', pathMatch: 'full', component: FeedComponent },
{ path: 'shoes', pathMatch: 'full', component: FeedComponent },
{ path: 'coats', pathMatch: 'full', component: FeedComponent },
{ path: 'shirts', pathMatch: 'full', component: FeedComponent },
{ path: 'pants', pathMatch: 'full', component: FeedComponent },
{ path: 'item/:id', component: FeedComponent },
];
#NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
That's how I tried to implement my childRoutingModule but it throws the error in the console: core.js:15724 ERROR Error: Uncaught (in promise): TypeError: undefined is not a function
TypeError: undefined is not a function
at Array.map ()
app.routing.module
const routes: Routes = [
{ path: '', pathMatch: 'full', loadChildren: './feed/feed.module#FeedModule' }
];
feed-routing.module
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { FeedComponent } from './feed.component';
const routes: Routes = [
{ path: '', pathMatch: 'full', component: FeedComponent },
{ path: 'shoes', pathMatch: 'full', component: FeedComponent },
{ path: 'coats', pathMatch: 'full', component: FeedComponent },
{ path: 'shirts', pathMatch: 'full', component: FeedComponent },
{ path: 'pants', pathMatch: 'full', component: FeedComponent },
{ path: 'item/:id', component: FeedComponent },
];
#NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class FeedRoutingModule { }
I want to have a separate routing module for each gross section on the site and I need link react to the url and indicate which module is active at the moment.
I would appreciate any other hints and best practices!
To setup feature route you have to import FeedRoutingModule into the module you want to use thoose route.
Below is my example
I have app.routing.ts (Main route)
export const routes: Routes = [
{ path: "", redirectTo: "home", pathMatch: "full" },
{ path: "home", component: HomeComponent },
//{ path: "**", redirectTo: "account", pathMatch: "full" },
//lazy load feature module
{ path: "account", loadChildren: "./account/account.module#AccountModule" },
{ path: "portal", loadChildren: "./portal/portal.module#PortalModule", canActivate: [AuthGuardService] },
{ path: "**", redirectTo: "account", pathMatch: "full" },
];
and app.module.ts
#NgModule({
declarations: [],
imports: [
RouterModule.forRoot(routes)
],
providers: [],
bootstrap: []
})
export class AppModule {}
So when I define child route in my feature module I have to done the same like app.module but using RouterModule.forChild
export const accountRoutes: Routes = [
{
path: "",
component: AccountComponent,
children: [
{ path: "login", component: LoginComponent },
{ path: "register-account", component: RegisterComponent }
]
}
];
import { NgModule } from "#angular/core";
import { CommonModule } from "#angular/common";
import { FormsModule, ReactiveFormsModule } from "#angular/forms";
import { RouterModule } from "#angular/router";
import { RegisterComponent } from "./register/register.component";
import { LoginComponent } from "./login/login.component";
import { AccountComponent } from "./account/account.component";
import { accountRoutes } from "./account.routing";
#NgModule({
declarations: [],
imports: [
RouterModule.forChild(accountRoutes) // use forChild
],
exports: [],
providers: []
})
export class AccountModule {}
Your paranet component need have tag: < router-outlet>< /router-outlet> then he knows will have a child component + route;
Here a exemple where i management childRoutes.
{
path: 'utente',
component: CenterViewComponent,
children: [
YYY_ROUTE,
XXX_ROUTE
...
]
}
Hope help u!

Application always serves '/' to express app

Have an angular 7 application and have implemented angular universal using node and express, and then deployed to firebase.
Having an issue when trying to load pages other than the root (/), which causes the server to return the html of the root (/) rather than the page the user requests.
Not sure from where the issue is originating (Angular, Angular Universal or Firebase).
This is my index.ts:
import * as functions from 'firebase-functions';
import 'zone.js/dist/zone-node';
import 'reflect-metadata';
import {renderModuleFactory} from '#angular/platform-server';
import {enableProdMode} from '#angular/core';
import * as express from 'express';
import {readFileSync} from 'fs';
enableProdMode();
const app = express();
const indexHtml = readFileSync(__dirname + '/index-server.html', 'utf-8').toString();
const {AppServerModuleNgFactory, LAZY_MODULE_MAP} = require('./main');
import {provideModuleMap} from '#nguniversal/module-map-ngfactory-loader';
app.engine('html', (_, options, callback) => {
// Always '/' (root path)
console.log('OPTIONS.REQ.URL', options.req.url);
renderModuleFactory(AppServerModuleNgFactory, {
// My index-server.html
document: indexHtml,
url: options.req.url,
extraProviders: [
provideModuleMap(LAZY_MODULE_MAP)
]
}).then(html => {
callback(null, html);
});
});
app.set('view engine', 'html');
app.set('views', __dirname);
app.get('*.*', express.static(__dirname + '/dist', {
maxAge: '1y'
}));
app.get('*', (req, res) => {
res.render(__dirname + '/index-server.html', {req});
});
exports.ssrApp = functions.https.onRequest(app);
This is my app-routing.module.ts:
import {RouterModule, Routes} from '#angular/router';
import {NgModule} from '#angular/core';
import {HomePageComponent} from './home-page/home-page.component';
import {ToursComponent} from './tours/tours.component';
import {MaltaComponent} from './malta/malta.component';
import {AboutComponent} from './about/about.component';
import {ContactComponent} from './contact/contact.component';
import {TourComponent} from './tours/tour/tour.component';
import {ErrorComponent} from './error/error.component';
import {BlogComponent} from './blog/blog.component';
import {BlogPageComponent} from './blog/blog-page/blog-page.component';
import {PageResolver} from './services/pages/page-resolver.service';
const AppRoutes: Routes = [
{
path: 'home',
component: HomePageComponent,
data: {
state: 'home',
pageId: 'home'
},
resolve: {
page: PageResolver
}
},
{
path: 'tours',
component: ToursComponent,
data: {
state: 'tours',
pageId: 'tours'
},
resolve: {
page: PageResolver
}
},
{
path: 'tours/:id',
component: TourComponent,
data: {
state: 'tour'
}
},
{
path: 'blog',
component: BlogComponent,
data: {
state: 'blogs',
pageId: 'blog'
},
resolve: {
page: PageResolver
}
},
{
path: 'blog/:id',
component: BlogPageComponent,
data: {
state: 'blog'
}
},
{
path: 'malta',
component: MaltaComponent,
data: {
state: 'malta',
pageId: 'malta'
},
resolve: {
page: PageResolver
}
},
{
path: 'about',
component: AboutComponent,
data: {
state: 'about',
pageId: 'about'
},
resolve: {
page: PageResolver
}
},
{
path: 'contact',
component: ContactComponent,
data: {
state: 'contact',
pageId: 'contact'
},
resolve: {
page: PageResolver
}
},
{
path: 'something-went-wrong',
component: ErrorComponent,
data: {
state: 'error',
pageId: 'error'
}
},
{
path: '',
redirectTo: '/home',
pathMatch: 'full'
},
{
path: '**',
redirectTo: '/something-went-wrong'
}
];
#NgModule({
imports: [
RouterModule.forRoot(AppRoutes, {
useHash: true,
scrollPositionRestoration: 'enabled',
initialNavigation: 'enabled'
})
],
exports: [RouterModule]
})
export class AppRoutingModule {
}
This is my firebase.json:
{
"hosting": {
"public": "dist",
"ignore": [
"firebase.json",
"**/.*",
"**/node_modules/**"
],
"rewrites": [
{
"source": "**",
"function": "ssrApp"
}
]
},
"functions": {
"predeploy": "npm --prefix \"$RESOURCE_DIR\" run build"
}
}
Would appreciate any help with this issue!
The issue is solved after removing useHash: true from the app-routing.module.ts.
Thanks to yeya for helping get to the solution.
Your issue is related to Browser URL styles
Based on this answer: Try change the rewrites from "function": "ssrApp" to "destination": "/index-server.html"
The requestindex-server.html will trigger the function.

Resources