I am fairly new to Angular and typescript but I have an Angular 6 project using Ionic 3 elements.
I am trying to import a library that is saved locally from the cdn from path ../lib/ionic.bundle.js into my project but I get template parse errors which indicates the module is not imported for that path.
Error: Template parse errors:
'ion-card-header' is not a known element:
1. If 'ion-card-header' is an Angular component, then verify that it is part of this module.
2. If 'ion-card-header' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '#NgModule.schemas' of this component to suppress this message. ("
<ion-card>
import { IonicApp, IonicModule } from '../lib/ionic.bundle.js';
const routes: Routes = [
{
path: 'create',
component: CreateComponent
},
{
path: 'edit/:id',
component: EditComponent
},
{
path: 'index',
component: IndexComponent
}
];
#NgModule({
declarations: [
CreateComponent,
IndexComponent,
EditComponent,
],
imports: [
IonicModule.forRoot(routes)
],
providers: [ ...]
})
export class AppModule { }
I am sure the file exists at that path but not being imported from some reason.
Is there a different way of importing the IonicModule?
You should try importing it from node_modules instead.
In command line in your project dir:
$ npm i ionic
After its installed ionic, then try importing from ionic-angular:
import { IonicModule } from 'ionic-angular'
Related
I am trying to use the uuid package in my TypeScript project, but I am encountering an error when I try to use the v4 method. The error message is: "Cannot read properties of undefined (reading 'v4')".
I have also included the #rollup/plugin-node-resolve, #rollup/plugin-commonjs, and #rollup/plugin-replace plugins in my rollup.config.js file in order to handle the uuid package, which is a Node.js-style package.
Here is my rollup.config.js file:
import typescript from "rollup-plugin-typescript2";
import { terser } from "rollup-plugin-terser";
import postcss from "rollup-plugin-postcss";
import image from "#rollup/plugin-image";
import json from "#rollup/plugin-json";
import commonjs from "#rollup/plugin-commonjs";
import nodeResolve from "#rollup/plugin-node-resolve";
import builtins from "rollup-plugin-node-builtins";
import replace from "#rollup/plugin-replace";
export default [
{
input: "src/index.ts",
output: {
file: "dist/bundle.js",
format: "cjs",
},
external: ["uuid"],
plugins: [
image(),
terser(),
postcss(),
nodeResolve(),
commonjs(),
replace({
require: "function(){}",
preventAssignment: true,
}),
builtins(),
typescript({
tsconfig: "tsconfig.json",
}),
json(),
],
},
];
In this project, I am using web components for my application. I am using the uuid package to generate unique IDs for these components, but I am encountering an error when I try to use the v4 method.
In one of my web component class, an example usage is like this:
import {v4 as uuidv4} from "uuid"
export class ExampleWebComponent extends HTMLElement{
...
private setInitialAttributes() {
this.setAttribute("customer-id", uuidv4());
}
...
connectedCallback() {
if (this.shadowRoot) {
this.setInitialAttributes();
}
}
}
And then I import this web component at App.ts file:
import { ExampleWebComponent } from "./web-components/ExampleWebComponent";
And define it to window.customElements:
function defineWebComponents() {
window.customElements.define("example-web-component", ExampleWebComponent);
}
export default defineWebComponents;
and I finally call the defineWebComponents function in index.ts file:
import defineWebComponents from "./App";
defineWebComponents();
const newComponent = document.createElement("example-web-component");
console.log(newComponent.getAttribute("customer-id");
I was expecting the v4 method to generate a new UUID. I was also expecting the #rollup/plugin-node-resolve, #rollup/plugin-commonjs, and #rollup/plugin-replace plugins to correctly handle the uuid package and allow me to use it in my TypeScript code.
I have an Angular SSR app that is not able to render the homepage via localhost:4000 while the backend node server is running.
So if I go to localhost:4000 it will start loading but never display anything nor finished loading. However, if I go to another page like 404 where I have a button to take me to the home page it does load it. Additionally, if I turn off the backend server it does load the homepage.
The app routes are handled like this:
//app-routing.module.ts
import { NgModule } from '#angular/core';
import { RouterModule, Routes } from '#angular/router';
import { GuardDashboardGuard } from './guard-dashboard.guard';
import { KYCGuard } from './guard-kyc.guard';
// More imports for other paths
const routes: Routes = [
{
path: 'profile-update',
canActivate: [GuardDashboardGuard, KYCGuard],
loadChildren: () =>
import('./pages/profile-update/profile-update.module').then((m) => m.ProfileUpdatePageModule),
},
// More paths with the same structure
{
path: '',
loadChildren: () => import('./pages/home/home.module').then((m) => m.HomePageModule),
},
{
path: 'faqs',
loadChildren: () => import('./pages/faq/faq.module').then((m) => m.FaqPageModule),
},
{
path: '',
redirectTo: '/',
pathMatch: 'full',
},
{ path: '**', redirectTo: '404' },
];
#NgModule({
imports: [
RouterModule.forRoot(routes, {
scrollPositionRestoration: 'enabled',
scrollOffset: [0, 0],
anchorScrolling: 'enabled',
relativeLinkResolution: 'legacy',
initialNavigation: 'enabledBlocking',
}),
],
exports: [RouterModule],
})
export class AppRoutingModule { }
I have tried fully deleting path: '', and the app redirected localhost:4000 to profile-update. Even if i delete profile-update I am still redirected to a Update Profile page.
Home page directory tree looks like:
.
├── home-routing.module.ts
├── home.module.ts
├── home.page.html
└── home.page.ts
// home-routing.module.ts
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { HomePage } from './home.page';
const routes: Routes = [
{
path: '',
component: HomePage,
},
];
#NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule],
})
export class HomePageRoutingModule {}
I am not sure what the cause of this error is or what code is relevant so I don't know what other code should be included in my question.
I also get a network error of crbug/1173575, non-JS module files deprecated.
and have found this Crbug/1173575, non-JS module files deprecated. chromewebdata/(index)꞉5305:9:5551 which was not very helpful to solve thebug.
Always I trying to GET '/' it shows static-root-component (component of my main page),
but when it is '/welcome' page immediately redirecting to '/' and also loading static-root-component instead of welcome-component
Initially I wanted to redirect users to welcome page if they aren't authorized, but login status only can be checked within JavaScript. After JS got info about login status it decides to redirect using location.replace("/welcome"), but... Angular again goes to '/'
"Funny" fact: there isn't any routing problems during debug with ng serve but it always happens with ng build
I don't know what's gone wrong and there is app.module.ts:
import { NgModule } from '#angular/core';
import { RouterModule, Routes } from '#angular/router';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { StaticRootComponent } from './static-root/static-root.component';
import { WelcomeComponent } from './welcome/welcome.component';
import { HttpClientModule } from '#angular/common/http';
import { HttpService } from './http.service';
import { BrowserAnimationsModule } from '#angular/platform-browser/animations';
const appRoute: Routes = [
{ path: '', component: StaticRootComponent, pathMatch: 'full' },
{ path: 'welcome', component: WelcomeComponent }
];
#NgModule({
declarations: [
AppComponent,
StaticRootComponent,
WelcomeComponent
],
imports: [
BrowserModule,
AppRoutingModule,
BrowserAnimationsModule,
RouterModule.forRoot(appRoute),
HttpClientModule
],
providers: [HttpService],
bootstrap: [AppComponent]
})
export class AppModule { }
I can drop any other Angular file if needed
In your code, change like below
const appRoute: Routes = [
{ path: '', component: StaticRootComponent },
{ path: 'welcome', component: WelcomeComponent },
{ path: '**', redirectTo: '' }
];
In the component file, inject this like below
import { Router } from '#angular/router';
constructor(
private router: Router
) {}
When you want do navigation use the below code instead of location.replace("/welcome")
this.router.navigate(['/welcome']);
Check the Module you trying to instantiate in the constructor of the Component linked to the Routing Path you are trying to access
In this case:
Our Component: example.component.ts
Our Module: HttpClientModule that contains HttpClient
Our Routing Path: "/example"
and make sure that Module is already existing in the app.module.ts , here is an example:
example.component.ts
import {HttpClient} from '#angular/common/http'; //child of HttpClientModule
#Component({selector: 'app-example',templateUrl: './example.component.html', styleUrls: ['./example.component.css']})
export class ExampleComponent{
constructor(private httpClient: HttpClient) { }
}
now let's see both examples of app module with and without the Module import and see the difference
app.module.ts
Without including HttpClientModule in imports array
import { AppComponent } from './app.component';
#NgModule({
declarations: [...],
imports: [BrowserModule,...],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
In this case loading the "/example" path will redirect you to the main page path which is usually "/" and that's because example.component.ts is using HttpClient (child of HttpClientModule) but not finding it in app.module.ts .
app.module.ts
Including HttpClientModule in imports array
import { AppComponent } from './app.component';
import { HttpClientModule} from '#angular/common/http'; //Import that module you willing to use
#NgModule({
declarations: [...],
imports: [BrowserModule,HttpClientModule,...], //add the module we currently using
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
In this case loading the "/example" path will work properly since we added the required module in app.module.ts.
If that's your case that would definitely fix your problem unless you have something else forcing the redirection to home page "index.html" or any other path, else if that didn't fix your problem read the following notes:
Make sure to check there are no redirections in the app-routing.module.ts routes array like this
const routes: Routes = [
{path: 'example', component: ExampleComponent},
{ path: '/example', redirectTo: '' }
];
it should only be like so
const routes: Routes = [
{path: 'example', component: ExampleComponent}
];
Also make sure there is no routing behaviour causing the redirection like #angular/router through something like this.router.navigate(['/'])
PS: SAME ISSUE COULD IMPLY IF YOU USING A SERVICE THAT'S USING A MODULE WHICH IS NOT ADDED TO MODULE IMPORTS IN app.module.ts
My project based on MEAN (Mongo, Express, Angular and NODEJS)... The last was a source of problem
#Shakthifuture, you said you want to see full code and I started answering:
"What you wanna to see else? My data and server files doesn't affec..."
and I've starting think "what if affect?": routing in whole of project works by Angular, but all new connection to the site pass NodeJS and Express, so I forgot about 404 case...
THE PROBLEM:
In server script file index.js of project's root folder a long time ago I've added code about what to do if entered path not found:
app.use(function (req, res, next) {
res.redirect('/');
// IF 404 NOT FOUND
});
and above of it something like:
app.get('/', function (req, res) {
res.sendFile(`${__dirname}/angular/index.html`)
});
// send index if path is '/'
but nothing for '/welcome', that's why redirecting happens
THE SOLUTION:
let's add the '/welcome' handler:
app.get('/welcome', function (req, res) {
res.sendFile(`${__dirname}/angular/index.html`)
});
(again index.html due to SPA)
I've got this routing file:
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { HomepageComponent } from './app/homepage/homepage.component';
import { SearchpageComponent } from './app/searchpage/searchpage.component';
import { EventPageComponent } from './app/eventpage/eventpage.component';
const routes: Routes = [
{
path: '',
component: HomepageComponent
},
{
path: 'search',
component: SearchpageComponent
},
{
path: 'event/:name/:id',
component: EventPageComponent
},
];
#NgModule({
imports: [
RouterModule.forRoot(routes)
],
exports: [RouterModule]
})
export class AppRoutingModule {
}
Whenever I try to navigate to an URL like http://localhost:4200/event/asa/123, it won't load the EventPageComponent (blank page) and Chrome gives me the following error in console:
Failed to load resource: the server responded with a status of 404 (Not Found) (http://localhost:4200/event/asa/inline.bundle.js)
It does that for every bundle.
Am I missing something?
It looks like your script reference in index.html is incorrect. It appears to be pointing at inline.bundle.js (relative to the current path) when it should be pointing at /inline.bundle.js (absolute). That's my best guess given your problem, I see nothing wrong with the Angular code (nor could anything in Angular produce this error).
If you're using something like webpack for bundling they no doubt have a solution for this.
I am using angular2 Final for development.
I have created 3 modules.
AppModule
ProjectModule
DesignerModule
Previously I had only AppModule,In Which I had imported following RoutingModule & it worked fine.
import {NgModule} from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import {ProjectManagerComponent} from './project-manager/project-manager.component';
import {DesignerComponent} from './designer/designer.component';
const appRoutes: Routes = [
{path: '',redirectTo: 'project-manager',pathMatch: 'full'},
{ path: 'project-manager', component: ProjectManagerComponent },
{ path: 'designer/:id', component:DesignerComponent }
];
#NgModule({
imports:[RouterModule.forRoot(appRoutes)],
exports:[RouterModule]
})
export class AppRoutingModule { }
export const routingComponents=[ProjectManagerComponent,DesignerComponent]
But recently I have created separate NgModules for ProjectManager & Designer.
I have kept ProjectManagerComponent,DesignerComponent inside declarations in their respective modules.
I want to know if it is possible to route to these modules using same routing configuration or do I need to change something.
My Routing is not working anymore.
any inputs?
instead of
export const routingComponents=[ProjectManagerComponent,DesignerComponent]
you can just
export const routing = RouterModule.forRoot(appRoutes);
Since you app.module.ts already knows about ProjectManagerComponent and DesignerComponent from their respective modules. All that is left is to teach it where to go and find them.
Inside of your app.module.ts you would have
// All the other imports
import {routing} from './app.routes;'
#NgModule({
imports:[routing, /*Other Modules*/],
})