i implemented child route but its giving me error and i am not able to open even my parent page which i mentioned in code, here is my code, error is mentioned at the end
`import {Component} from '#angular/core';
#Component({
template:`<div style="width:350px;hight:200px;background-color:#00ff00">
<h1>Create Places</h1>
</div>
<a [routerLink]="['/placeDetail']">PlaceDetail</a>
<div>
<router-outlet></router-outlet>
</div>
`
})
export class PlaceComponent{}
`
import { ModuleWithProviders } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { DashboardComponent } from '../app/components/dashboard.component';
import {NeighbourhoodComponent} from '../app/components/neighbourhood.component';
import {UserProfileComponent} from '../app/components/userProfile.component';
import {PlaceComponent} from '../app/components/place.component';
import {PlaceDetailComponent} from '../app/components/placeDetail.component';
const appRoutes: Routes = [
{
path: '',
redirectTo: 'dashboard',
pathMatch: 'full'
},
{
path: 'dashboard',
component: DashboardComponent
},
{
path:'neighbourhood',
component:NeighbourhoodComponent
},
{
path:'userprofile',
component:UserProfileComponent
},
{
path:'place',
component:PlaceComponent,
children:[
{
path:'placeDetail',
component:PlaceDetailComponent
}
]
}
];
export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);
once i will click on link it should go to placeDetailComponent but it is giving me error
EXCEPTION: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'place'
issue solved, i had Angular 2.1, just updated to 5 and it is working.
Related
I created a project with Vite, Pinia and Vue-router. Everything works perfectly in development, but when I access the build, only the main path works. All other redirects return 404:
"Failed to load resource: the server responded with a status of 404 ()"
"crbug/1173575, non-JS module files deprecated.
(anonymous) # VM10:6789"
Any idea what could be happening?
*** Main.js ***
import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
// Font Awesome
import { library } from '#fortawesome/fontawesome-svg-core'
import { fas } from '#fortawesome/free-solid-svg-icons'
import { far } from '#fortawesome/free-regular-svg-icons'
import { fab } from '#fortawesome/free-brands-svg-icons'
import { FontAwesomeIcon } from '#fortawesome/vue-fontawesome'
//Router
import router from './router'
//Pinia
import { createPinia } from 'pinia'
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
library.add(fas, far, fab);
const pinia = createPinia();
pinia.use(piniaPluginPersistedstate);
createApp(App)
.use(pinia)
.use(router)
.component('fa', FontAwesomeIcon)
.mount('#app')
*** App.vue ***
<script setup>
import { RouterView } from "vue-router";
</script>
<template>
<RouterView />
</template>
*** router/index.js ***
import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '../stores/AuthStore';
const router = createRouter({
history: createWebHistory(),
routes: [
{
path: "/katriumweb/login",
name: "login",
component: () => import("#/views/Login.vue")
},
{
path: "/katriumweb/playground",
name: "playground",
component: () => import("#/views/Playground.vue")
},
{
path: "/katriumweb/",
name: "home",
component: () => import("#/views/Home.vue"),
meta: {
authRequired: true
}
},
{
path: "/katriumweb/vehicleupdate",
name: "vehicleupdate",
component: () => import("#/views//workflows/VehicleUpdate.vue"),
meta: {
authRequired: true
}
}
],
});
router.beforeEach(async (to, from, next) => {
const authStore = useAuthStore();
let token = authStore.user? authStore.user.TOKEN : false;
const checkToken = await fetch("*******", {
method: "GET",
headers: {
"Token": `${token}`
}
})
if (to.meta.authRequired) {
if (!checkToken.ok || !token) {
localStorage.clear();
next("/katriumweb/login");
} else {
next();
}
} else {
next();
}
})
export default router;
*** vite.config.js ***
import { fileURLToPath, URL } from "node:url";
import { defineConfig } from "vite";
import vue from "#vitejs/plugin-vue";
// https://vitejs.dev/config/
export default defineConfig({
base: "/katriumweb/",
plugins: [vue()],
resolve: {
alias: {
"#": fileURLToPath(new URL("./src", import.meta.url)),
},
},
});
Since the app itself only has an index.html file and everything else is done via javascript, when you navigate to /mypage it tries to grab another html file.
The Vue Router createWebHistory works this way. A simple fix is to use createWebHashHistory, which uses a hash in order to create the routing.
Otherwise, more solutions are available on the documentation (eg. Netlify supports a redirect property to handle this).
The docs: https://router.vuejs.org/guide/essentials/history-mode.html
Production build looses something.
I have Vue 3.2.33 project; vite: 2.9.5
When running dev-server all the template renders fine:
App.vue:
<template>
<div id="menu">
<nav class="navbar">
<router-link class="navbar__link" to="/">{{ state.reg }}</router-link>
<router-link class="navbar__link" to="/Information">{{
state.info
}}</router-link>
<router-link class="navbar__link" to="/Subscribers">{{
state.subs
}}</router-link>
</nav>
<LocaleSwitcher />
</div>
<router-view></router-view>
</template>
router config file
import { createRouter, createWebHistory } from "vue-router";
import Information from "#/views/Information.vue";
import Search from "#/views/Search.vue";
import Subscribers from "#/views/Subscribers.vue";
import { useStore } from '#/stores/store'
const routes = [
{
path: "/",
name: "Search",
component: Search,
},
{
path: "/information",
name: "Information",
component: Information,
},
{
path: "/subscribers",
name: "Subscribers",
component: Subscribers,
},
];
const router = createRouter({
history: createWebHistory(),
routes
});
router.beforeEach((to) => {
const store = useStore()
if (!store.hasGroup && to.path !== '/') {
return '/'
}
})
export default router;
vite.config.ts
import { fileURLToPath, URL } from "url";
import vueI18n from "#intlify/vite-plugin-vue-i18n";
import { defineConfig } from "vite";
import vue from "#vitejs/plugin-vue";
import path from "path";
export default defineConfig({
plugins: [
vue(),
vueI18n({
include: path.resolve(__dirname, "./src/locales/**"),
}),
],
resolve: {
alias: {
"#": fileURLToPath(new URL("./src", import.meta.url)),
},
}
});
but if I run build for production and run preview server, none of router components(router-link and router-view) render. Reading vite and vue-router documentation does not clarify anything yet. I would be grateful for any help, given that I am often just inattentive
I am trying to push from one component to another using vue routes but am having issues!
This is my router->index.js:
import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '#/pages/HelloWorld'
import GroupStart from '#/pages/GroupStart'
import NotFound from '#/pages/NotFound'
Vue.use(Router)
export default new Router({
routes: [{
path: '/',
name: 'HelloWorld',
component: HelloWorld
},
{
path: '/groupstart',
name: 'GroupStart',
component: GroupStart
},
{
path: '*',
name: 'Notfound',
component: NotFound
}
],
mode: 'history'
})
Now, from my helloworld component I am trying to do this:
<template>
<div class="hello">
<h1>{{ msg }}</h1>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
data () {
return {
msg: 'This is the startpage'
}
}
}
this.$router.push({ path: '/groupstart' })
</script>
When doing so I get this error:
Uncaught TypeError: Cannot read property 'push' of undefined
at eval (HelloWorld.vue?18db:17)
Not sure what I am doing wrong and hoping for help :-)
Thanks in advance.
you need to write this this.$router.push({ path: '/groupstart' }) inside some hook or method. if you want to do it right away when page is loaded, you can do something like this
<script>
export default {
name: 'HelloWorld',
data () {
return {
msg: 'This is the startpage'
}
},
mounted () {
this.$router.push({ path: '/groupstart' })
}
}
</script>
Starting from a clean ionic 4 project (using ionic start --type=angular and the template blank), I'm trying to create a custom angular component that can be used on multiple pages.
However if I use ionic generate component and try too use the generated component test in homepage.html by inserting <app-test></app-test> I get the error:
core.js:1673 ERROR Error: Uncaught (in promise): Error: Template parse errors:
'app-test' is not a known element:
1. If 'app-test' is an Angular component, then verify that it is part of this module.
2. If 'app-test' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '#NgModule.schemas' of this component to suppress this message. ("="_blank" rel="noopener" href="https://ionicframework.com/docs">docs will be your guide.
ERROR Error: Uncaught (in promise): Error: Template parse errors:
'app-test' is not a known element:
1. If 'app-test' is an Angular component, then verify that it is part of this module.
2. If 'app-test' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '#NgModule.schemas' of this component to suppress this message. ("="_blank" rel="noopener" href="https://ionicframework.com/docs">docs will be your guide.
Here is what my files look like: app.module.ts
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { RouteReuseStrategy } from '#angular/router';
import { IonicModule, IonicRouteStrategy } from '#ionic/angular';
import { SplashScreen } from '#ionic-native/splash-screen/ngx';
import { StatusBar } from '#ionic-native/status-bar/ngx';
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
import { TestComponent } from './test/test.component';
#NgModule({
declarations: [AppComponent, TestComponent],
entryComponents: [],
imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule],
providers: [
StatusBar,
SplashScreen,
{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
],
bootstrap: [AppComponent]
})
export class AppModule {}
app-routing.module.ts
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
const routes: Routes = [
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home', loadChildren: './home/home.module#HomePageModule' },
];
#NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
test.component.ts
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.scss']
})
export class TestComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}
home.page.ts
import { Component } from '#angular/core';
#Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage {
}
home.module.ts
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { IonicModule } from '#ionic/angular';
import { FormsModule } from '#angular/forms';
import { RouterModule } from '#angular/router';
import { HomePage } from './home.page';
#NgModule({
imports: [
CommonModule,
FormsModule,
IonicModule,
RouterModule.forChild([
{
path: '',
component: HomePage
}
])
],
declarations: [HomePage]
})
export class HomePageModule {}
home.page.html
<ion-header>
<ion-toolbar>
<ion-title>
Ionic Blank
</ion-title>
</ion-toolbar>
</ion-header>
<ion-content padding>
The world is your oyster.
<p>If you get lost, the <a target="_blank" rel="noopener" href="https://ionicframework.com/docs">docs</a> will be your guide.</p>
<app-test></app-test>
</ion-content>
And the folder structure as an image
I have tried out several things by now and one work around I found is creating a src/app/shared.module.ts file and declaring and exporting the TestComponent there, and then importing the SharedModule in every page I want to use the component.
However I feel like this work around is not ideal, and there is something I am missing in how to do it cleaner. Any ideas?
Your shared module workaround is actually a good practice in angular and you should stick with that.
For reference: https://angular.io/guide/sharing-ngmodules
I have an error in console after authentication. After reload page CreateChartComponent page start working. Error just happen in authentication process.
Uncaught (in promise): Error: Cannot find primary outlet to load 'CreateChartComponent'
This is the login function.
login(event, username, password): void {
event.preventDefault();
this.authService.login(username, password).subscribe(
res => {
this.router.navigate(['drawing']);
},
err => {
// todo: handle error with a lable
console.log(err);
if (err.ok === false) {
this.errorMessage = 'Error logging in.';
}
});
}
}
Aditional information:
I send clear mode of code where I get same issue.
It's Router code:
// Import our dependencies
import { Routes } from '#angular/router';
import { AppComponent } from './app.component';
import { LoginComponent } from './home/login/login.component';
import { CreateChartComponent } from './home/drawing/create-chart.component';
import { AuthGuard } from './auth.guard';
// Define which component should be loaded based on the current URL
export const routes: Routes = [
{ path: '', component: CreateChartComponent, pathMatch: 'full', canActivate: [AuthGuard] },
{ path: 'login', component: LoginComponent },
{ path: 'drawing', component: CreateChartComponent, canActivate: [AuthGuard] },
];
and its create-chart.component.ts
import {
Component,
OnInit,
} from '#angular/core';
#Component({
selector: 'np-chart-create',
templateUrl: './create-chart.component.html',
styleUrls: ['./create-chart.component.css']
})
export class CreateChartComponent implements OnInit {
ngOnInit() {
}
}