Angular 2 App Reloading on Route Change - angularjs

I have an angular 2 app with the following routes:
#RouteConfig([
new Route({ path: '/', component: Home, name: 'Home', useAsDefault: true}),
new Route({ path: '/employees', component: ViewEmployees, name: 'ViewEmployees'}),
new Route({ path: '/employees/add', component: AddEmployee, name: 'AddEmployee'}),
])
among others. When I change routes in the following way:
<a [routerLink]="['ViewEmployees']">View Employees</a>
There are no issues. I can change routes in this way from either the home page or the AddEmployee route. The issue comes when I'm in the AddEmployee route and try to change routes in a programmatic way like this:
import {Router} from 'angular2/router';
...
constructor(private _router:Router) {}
...
navigate() {
this._router.navigate(['ViewEmployees']);
}
it doesn't work. It sends me to the ViewEmployees view and then reloads the entire app. If I do that same programmatic route change from the Home component I don't have any issues; the app doesn't reload.
Does anyone have any ideas why it would do this in just this one case? I need it to work so that I can save the employee that's added and then go back to the employee list view.
Thanks in advance for the help!

Do you call navigate() from within a <form> Tag?
I had the same Problem. There exist some issues describing this behavior on Angular2s GitHub but they are all closed because they belong to the old router. The page reload seems to occur when you use router.navigate() inside a function called by a submit button inside a form. This can cause the browser to append a ? at the end of the URL and reload it.
The solution is very simple: Just return false at the end of your navigate() function. This prevents the bowser to use it's default action when submitting forms. Usually angular stops such default behavior but strangely not in this case.

Have you set the <base href>?
As mentioned in the Router guide
Add the following code to your index.html after the opening head tag:
<base href="/">

From RouterLink docs:
The first route name should be prepended with /, ./, or ../. If the route begins with /, the router will look up the route from the root of the app. If the route begins with ./, the router will instead look in the current component's children for the route. And if the route begins with ../, the router will look at the current component's parent.
Use:
<a [routerLink]="['/ViewEmployees']">View Employees</a>

Related

How to navigate to child routes within a dynamic (slug) route in SvelteKit

I have the following route structure
src/routes/[slug]/results
src/routes/[slug]/about
I can't figure out how to link to the routes in SvelteKit. The routes themselves work when I access them through the browser navigation bar.
How can I create a simple links on the [slug] page, that will link to the child routes?
Both below link to the root:
results
results
Tried something like below, but that didn't work.
results
results
I assume it's something similar, but the SvelteKit documentation on routing and advanced routing don't mention anything related to navigation within dynamic routes.
Would just add the parameter to the link:
<script>
import { page } from '$app/stores';
</script>
Results
I figured it out, it was a bit hidden in the documents (and I'm a starter, so not fully aware of all the concepts yet).
In +page.js:
/** #type {import('./$types').PageLoad} */
export function load({ params }) {
return {
slug: params.slug
};
}
In +page.svelte:
<script>
export let data;
</script>
results
share

How to display different components on single page in angular

I have divided my landing page into small components and now I want to show all of my components on landing page and also display some of the components on different pages/routes. I tried adding it with the routes as childeren but it doesnt work with me. Can anyone help me with this?
const routes: Routes = [
{path:'', component:BannerComponent, children:[
{path:'',component:VideoComponent}]},
{path:'home', component:AboutComponent}
];
I want to create a main url directory where some of my components should show and when the user enter another path it should show only those components that are added for that path.
Angular offers you a simple way to do this.
When creating a component, it gives you this:
#Component({
selector: 'ab-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.scss'],
})
As we can see there is a selector called 'ab-header'.
Just go to the html and paste it in a tag like this.
<ab-header></ab-header>
Hope this helps you
I have followed these steps.
First Create a new component
ng g c homePage
add the desired components in the homePage.component.html
Inlude it in the routes
const routes: Routes = [
{path:'', component:HomePageComponent}
];

Angular 2 for non-SPA (static pages)

All the samples I come across on the web are SPAs, I'm wondering if Angular 2 has a build-in way to handle static pages. Specifically, let's say I use Angular 2 to build a blog site, and I wish users could go directly to a particular post without going through the default home component, (which also incidentally, loads a lot of server side config). I mean, how do I enable user to go to http://server/posts/:id directly, without 404 showing up or configure a ** page for unreachables.
Just need some directions, thanks.
Let's say my folder structure goes like this
/posts
/shared
/users
and my main router goes like this
#RouteConfig([
{ path: './shared/...', name: 'Shared', component: SharedComponent },
{ path: './users/...', name: 'Users', component: UserComponent },
{ path: './posts/...', name: 'Posts', component: PostComponent }
])
and post router goes like this
#RouteConfig([
{ path: '/', name: 'List', component: ListComponent, useAsDefault: true },
{ path: '/:id', name: 'Post', component: PostComponent },
{ path: '/:id/gallery', name: 'Gallery', component: GalleryComponent },
{ path: '/:id/comments', name: 'Comments', component: CommentListComponent },
])
I think I understand your problem. You need to configure your web server software (e.g., Apache) a certain way, this is not an Angular2 configuration issue. You need to configure your web server so that whenever it receives url requests like / or /posts or /posts/123 that it serves your main index.html file. Then Angular will automatically show the right content when it starts up.
Seems like you are looking for routers. Have a look at the docs:
Off. Guide and Router Tutorial. It's used like this:
#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 { }
Its quite hard to tell the perfect answer as you are asking for without going through the default home component(I am not sure what do you mean by that).
AFAIK, in angular2 you can have one component which can define/set routes for other components and so their relevant view.
Let's say after defining routes in a single component, if you go with the HashLocationStrategy like below,
bootstrap(AppComponent, [provide(LocationStrategy,{useClass: HashLocationStrategy}]);
Angular2 will be able to provide you required route and so you don't need to configure server with some extra route setting. Then, you will be able to access required resource at http://server/#/posts/:id
If you go with PathLocationStrategy like below,
bootstrap(AppComponent, [provide(APP_BASE_HREF).toValue(location.pathname)]);
For this configuration angular2 will not be able to provide you required route and so server side routing needs to be configured. Then, you will be able to access required resource at http://server/posts/:id
So In short if required/asking path exits, it will take users to that path.
I know I'm a year late, but your issue is that whatever web-server you're using needs to rewrite urls to the index.html of your web-app. If it did that, then when you went to server/hero/123, the web-server would direct it to the index.html of your web-app, and your web-app would use the router to go to the HeroDetail component, without showing the default home component. Because you don't have the rewrite, the web-server is not even starting the angular app and is instead trying to serve the file server/hero/123, which doesn't exist and therefore it gives you a 404.
FYI this would still be a SPA (single page application).

Backbone routing keeping hashtags when navigate()

Hello here is my scenario.
I have these routes
routes: {
"": "show_group_list",
"!/group/:_id/": "show_group",
},
and here is my navigate function:
App.app.navigate('!/group/'+group.get('_id')+'/', { trigger: true });
when the function is triggered, on the address bar it shows localhost/group/1 instead of localhost/#!/group/1. The problem is that when I refresh the page I don't get the initial page anymore (mine is a single page app)
How can I hack navigate() so that it keeps the hashtag?
Ok, This was easy, I had pushState enabled. Disable pushState and you'll have back the hash

Backbone route to /

I have a Backbone Router:
class X.Routers.Main extends Backbone.Router
routes:
'/': 'home'
'pageb': 'actionb'
'pagec': 'actionc'
Pages B and C work, but navigating to http://domain.ext/ results in a page reload instead of triggering the right route.
How can I prevent this?
You can either set "*path": "home" as your last route which will make it a default route or set "" (instead of "/")as your first route (which means root directory)
your base url path IS NOT "/", BUT "" (empty string)
I usually add optional "/" at the end of each route configuration, just in case
I also usually add default action handler at the end of configuration
So my routes configuration would be like:
routes = {
'': 'home',
'pageb(/)': 'actionB', // so /pageb or /pageb/ will call the same function
'pagec(/)': 'actionC', // so /pagec or /pagec/ will call the same function
'*action': 'defaultAction' // you can use it to render 404, or call home function
}
Hope this help

Resources