angular2 new router not loading from URL - angular2-routing

I have just upgraded from router-deprecated to "#angular/router": "3.0.0-alpha.8". I have everything working inside the application but it's not working when I navigate to a URL.
For example, I use this routerLink:
<a [routerLink]="['/app/dashboard']">DashBoard</a>
which produces this URL:
http://localhost:54675/app/dashboard
And that view loads with no problem.
However, if I just enter that URL in the browser and press return I get a blank white page. Nothing in the console and the source is empty.
I am using the default HTML5 locationStrategy - not the hash (#).
This worked with router-deprecated.
I can't figure out what I could be doing wrong since everything else is working.
When I navigate to a fill URL I notice that I get a 404 error in the console. That's because nothing on the server matches this URL, but it needs to load the app then route to that URL.
Here are my route files:
app.routes.ts:
export const routes: RouterConfig = ([
{ path: '', component: SplashComponent },
{ path: 'login', component: SplashComponent },
...MainRoutes
]);
export const APP_ROUTER_PROVIDERS = [
provideRouter(routes)
];
main.routes.ts
export const MainRoutes: RouterConfig = [
{
path: 'app',
component: MainLayoutComponent,
children: [
{ path: 'dashboard', component: DashboardComponent},
{ path: '', component: DashboardComponent },
{ path: 'user', component: AccountEditComponent },
{ path: 'admin', component: ManageComponent }
]
}
];

My Angular2 app was hosted in an DotNet Core application. I had to configure it to redirect to index.html on URLs that returned 404s. I followed this article:
http://asp.net-hacker.rocks/2016/04/04/aspnetcore-and-angular2-part1.html

Related

Failed to fetch dynamically imported module: http://host/sistem/views/reports/reportSales.vue

I created dynamic routes and locally it works perfectly, but when I publish the application it is returning
Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec.
index-d9e4afe8.js:9 TypeError: Failed to fetch dynamically imported module: http://host/sistem/views/reports/reportSales.vue
/sistem/home:1 Uncaught (in promise) TypeError: Failed to fetch dynamically imported module: http://host/sistem/views/reports/reportSales.vue
this is my routes index.js structure
import { createRouter, createWebHistory } from "vue-router";
import TopMenu from "../layouts/top-menu/Main.vue";
import Login from "../views/admin/login/Main.vue";
import Home from "../views/admin/home/Main.vue";
import Exit from "../views/admin/exit/Main.vue";
import hosts from "#/utils/hosts";
async function createRouterInstance() {
var data = await searchRoutes();
let lstRoutes = [
{
path: `${hosts.app}` + "/home",
name: "Home",
component: Home,
},
{
path: `${hosts.app}` + "/exit",
name: "Exit",
component: Exit,
},
];
for (var i = 0; i < data.length; i++) {
let dsPath = `${hosts.app}/${data[i].pagename}`;
let pathComponent =
"../views/" + data[i].path + "/" + data[i].pagename + ".vue";
lstRota.push({
path: dsPath,
name: data[i].pagename,
component: () => import(pathComponent),
});
}
let routes = [
{
path: `${hosts.app}/`,
name: "Login",
component: Login,
},
{
component: TopMenu,
children: lstRota,
},
];
const router = createRouter({
history: createWebHistory(),
routes,
scrollBehavior(to, from, savedPosition) {
return savedPosition || { left: 0, top: 0 };
},
});
return router;
}
export default await createRouterInstance();
previously I had vite 2, but researching the error, I updated to vite 4.0.0-alpha.6 and the same error continued, I also tested changing to createHashWebHistory in my route, but the same error also occurs and why I also tried importing without the .vue extension, but it still persists

clear URL when route changes

I've got Vue app with this router file in it:
const routes = [
{
path: '/',
component: () => import('layouts/MainLayout.vue'),
children: [
{ path: '', component: () => import('pages/IndexPage.vue') },
{ path: '/contacts', component: () => import('pages/ContactsPage.vue') },
{ path: '/settings', component: () => import('pages/GeneralSettings.vue') },
]
},
{
path: '/:catchAll(.*)*',
component: () => import('pages/ErrorNotFound.vue')
}
]
export default routes
Inside the IndexPage I've created this method to show the id in the URL , so I can use it later:
const setURL = (item: Store) => {
const searchURL = new URL(window.location.toString());
searchURL.searchParams.set('itemid', item.id);
window.history.pushState({}, '', searchURL);
}
This method works just fine, but when I try to open eg.: the Contact page the URL looks like this:
http://localhost:8080/?itemid=1#/contacts
This is not working, because the URL should be the following:
http://localhost:8080/#/contacts
Is there any way to remove the itemid when clicking a link?
I'm using Quasar and composition api.
I think the main problem is in the setUrl function.
When using vue-router, I suggest you try not to interfere with the url manually as much as possible.
If you want to add a query to the url without refreshing the page, you can use the router.replace() method.
import { useRouter } from "vue-router"
const router = useRouter()
const setURL = (item: Store) => {
router.replace({ query: { itemId: item.id } })
}
Your routes should work fine when you edit them this way.

How to make index.js Vue router dynamic?

I'm trying to make index.js in vue.js dynamic instead of me having to go in a manually add a page path or name.
What i'm hoping for is to use $route from the data (see screenshot ) in router > index.js so something like the below if possible.
{
path: $route.path,
name: $route.name,
component: () =>
import(/* webpackChunkName: "about" */ "../views/mainPages.vue"),
props: true,
},
instead of having to manually add a new block every time. See example
{
path: "/jobs/other-jobs",
name: "other-jobs",
component: () =>
import(/* webpackChunkName: "about" */ "../views/mainPages.vue"),
props: true,
},
Any help would be greatly appreciated.

After update angular version 8 to 11, app is not running

I have an Angular app version update from 8 to 11. This router is not working after the update. Show blank page when application is run. There is no error in the compilation and browser consoles. How to solve the problem?
export const AppRoutes : Routes = [
{ path: 'login', component: LoginPageComponent }
{ path: '', component: MainComponent},
{ path: '', component: MainComponent, children: [
{ path: 'test-one', loadChildren: () => import('./TestOne/TestOne.module').then(m => m.TestOneModule)},
{ path: 'test-two', loadChildren: () => import('./TestTwo/TestTwo.module').then(m => m.TestTwoModule), canActivate: [AuthGuard], runGuardsAndResolvers: 'always'}
]},
{ path: ':pageslug', component : MainComponent },
{ path: '**', component : MainComponent }
];
There are some breaking changes concerning router in Angular 11 as follows:
router: * The initialNavigation property for the options in RouterModule.forRoot no longer supports legacy_disabled, legacy_enabled, true, or false as valid values. legacy_enabled (the old default) is instead enabledNonBlocking
enabled is deprecated as a valid value for the RouterModule.forRoot initialNavigation option. enabledBlocking has been introduced to replace it
router: preserveQueryParams has been removed, use queryParamsHandling=”preserve” instead
router: If you were accessing the RouterLink values of queryParams, fragment or queryParamsHandling you might need to relax the typing to also accept undefined and null. (#39151)
Pls see :
https://medium.com/swlh/angular-11-in-depth-9a7372b4a600

want to navigate from one page to another page using child module

Child Module
​const routes: Routes = [
{ path: '', component: ProcComponent,
children:[{
path: '/LoadProcResultsdata/:procResults', component: ProcResultsComponent,
}]
}
];
App.Module.ts
​const routes: Routes = [
{ path: 'app', component: AppComponent },
{ path: 'home', component: HomeComponent },
{ path: 'treeview', component: TreeViewComponent },
{path:'Proc', loadChildren:'app/proc/Proc.Module#ProcModule'}
];
My code
this.router.navigate(['/LoadProcResultsdata/'],{ queryParams: { procResults:this.results } });
But I am getting following error.
core.umd.js:3064 EXCEPTION: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'LoadProcResultsdata'
Error: Cannot match any routes. URL Segment: 'LoadProcResultsdata'
There are couple of issues,
remove front / from the path,
children:[{
path: '/LoadProcResultsdata/:procResults', component: ProcResultsComponent,
}]
Also you need to use route params rather query params, so you can use below,
this.router.navigate(['/LoadProcResultsdata', this.results]);
I am assuming this.results is some ID, so the resulting url becomes
/LoadProcResultsdata/<id>
Read more abour route parmeters here.
Update:
you can do that but not with route params, just with queryParams, remove :procResults, and use similar code like below,
let extra: any = ['abc','xyz'];
let navigationExtras: NavigationExtras = {
queryParams:extra
};
this.router.navigate(['/LoadProcResultsdata'],navigationExtras);
and in the navigted component subscribe to ActivatedRoute queryParams,
constructor( private route: ActivatedRoute) {
route.queryParams.subscribe(params => {
console.log(params);
})
}
Check this Plunker!!
another Plunker with Lazy loaded module.

Resources