It doesn't do me the right thing, Url changes it but the page doesn't render it.
I have two home and jobs routes, I watched doc. From Angular, but not working
This is routing.module
import { Route, Routes, RouterModule } from '#angular/router';
import { NavigationJobsComponent } from './../jobs/navigation-jobs/navigation-jobs.component'
import { InputFieldComponent } from './components/input-field/input-field.component'
export const routes: Routes = [
{
path: "",
component: InputFieldComponent
},{
path: "jobs",
component: NavigationJobsComponent
},
];
This is dependency from module
RouterModule.forRoot(routes),
Surely someone has been hit by this before. Maybe this topic will be useful to someone, Excuse the emotions
"but the page doesn't render it"
It seems like you forgot to add <router-outlet></router-outlet> in your AppComponent's Template
Have created a Stackblitz Demo for your reference
As KShewengger has said above, look in your template if you're using the <router-outlet></router-outlet>. If you're using a navbar to navigate between routes, then you have to put the <router-outlet></router-outlet> in your navbar Component.
If not, try to use the <router-outlet></router-outlet> in your app.component.html (down if possible).
It would be nice if you could share your whole code about your issue, for better understand where could be it.
Related
Hello I am currently doing the front end of my project.
I would like to render components dynamically depending on the route.
For example I have a /auth route then it links to /auth/login or /auth/register or /auth/forgot.
This is the place where I would like to see the different components rendered.
I was assuming I can use router-view to loud the different components into the DOM.
<template>
<head-comp></head-comp>
<router-view></router-view>
<footer-comp></footer-comp>
</template>
<script>
import HeaderComp from '../components/Universal/HeaderComp.vue'
import FooterComp from '../components/Universal/FooterComp.vue'
export default
{
components: {
'header-comp' : HeaderComp,
'footer-comp' : FooterComp
}
}
</script>
This is the router
{
path: '/auth',
name: 'auth',
component: () => import('../views/AuthView.vue'),
children: [
{
path: 'login',
name: 'auth.login',
component: () => import('../components/Authentication/LoginComp.vue')
},
],
}
And this is the vue file that will contain the login form.
<tempalte>
Login
</tempalte>
<script>
</script>
The error I get with my current approach is this.
The requested module '/src/components/Authentication/LoginComp.vue?vue&type=tempalte&index=0&lang.tempalte' does not provide an export named 'default'
I was thinking I could just use different views for example, login/registerView.vue instead of having them in components but I feel like this is messier and would make it harder to maintain in the future.
Thanks for reading and looking forward to your responses.
You have typos in your LoginComp.vue component.
<tempalte>
Login
</tempalte>
should be
<template>
Login
</template>
In AngularJS, for routing purposes, we define states with children which makes it possible to switch between views with the result that each view is always rendered in one container:
$stateProvider.state("communication.create-message", {
url: ...,
templateUrl: ...,
menu: ...,
parent: "communication",
ncyBreadcrumb: {
label: "Create Message"
}
});
Whichever state we choose - the view is always rendered within one container that has ui-view attribute.
I'm trying to achieve the same in Angular 2 or above, but I have no idea of how to reproduce the above-stated functionality.
In app.component.ts we have router-outlet where component templates get rendered.
Say, we have many nested child routes - is it possible to render all of them within this outlet ?
What would the code in app-routing.module.ts look like in this case ?
Could anyone please give a working example of how to go about it ?
Step 1 : Import Routes from #angular/router
in app.module.ts .. import Routes. You have to write
import {Routes} from '#angular/core'
Step 2 :
Add all the routes you want to set up in an array pf type Routes like :
this is for informing angular all the routes in your app. Each route is a javascript object in this array.
const appRoutes : Routes = [
{path : 'communication-route'}
]
always you have to give path , this what you enter after your domain like "localhost :4200/communication-route".
Step 3: Add the action to route i.e what happens when this path is reached.
const appRoutes : Routes = [
{path : 'communication-route'} , component :communicationroutecomponent
]
here i have given the component name "communicationroutecomponent" , i.e this component will be loaded when the path "/communication-route" is reached
Step 4: Register your routes in your app
To do this you will have to do new import in app.module.ts
import {RouterModule} from '#angular/router'
Routermodule has special method forRoot() which registers our routes .
In our case we will have to write this piece of code in
imports :[
RouterModule.forRoot(appRoutes)
]
Our routes are now registered and angular knows our routes now.
Step 5 : Where to display the route content i.e the html content of you route page.
For this angular has directive .
We need to include where we want to load our content i.e in the html.
<a router-outlet="/communication-route"></a>
Navigating to routes :
angular gives a directive for this routerLink
so if we want to navigate to users component , you can give this in your html element:
routerLink="/communication-route"
I hope i was able to explain how this works.
Your code should be as follows
export const ComRoute: Routes = [
{
path: 'communication-route',
children: [
{ path: 'communication', component: communicationComponent },
{ path: ':child1', component: child1Component },
{ path: ':child1/field', component: child1Component}
]
}
];
First of all, states are not an official AngularJS concept. They come from ui-router, which began life as an alternate to the simplistic built in router.
Eventually, ui-router became the de facto standard for routing in AngularJS while the official ng-route module was extracted into a separate, optional library by the Angular team.
ui-router, is complex but exceptional and has earned what is in my view well deserved popularity and success. This success has led to its expansion to support additional platforms enabling the same powerful state based structure in applications written for frameworks such as React.
It is now available for Angular (formerly known as Angular 2).
You can read the documentation and see how to get started on https://ui-router.github.io/ng2
Here is a snippet from the src/app/app.states.ts module of the official example repository
export const loginState = {
parent: 'app',
name: 'login',
url: '/login',
component: LoginComponent,
resolve: [
{ token: 'returnTo', deps: [Transition], resolveFn: returnTo },
]
};
As we can see, there are compatible concepts available, including what looks like a nice evolution of the resolves API which allows function oriented injection which was generally simpler than class based injection in ui-router with AngularJS.
Note, I have not used it in an Angular project.
Taking my first stab at Vue2 and am stuck with routes.
Basically, when I added <router-view></router-view> to index.html I started receiving the exception:
[Vue warn]: Failed to mount component: template or render function not
defined.
found in
---> <Anonymous>
<Root>
GitHub Code Link: https://github.com/kernelcurry/httpverbs-site/tree/c56ba0a45445f7d28c31cb6928471da3619a3327
I even looked up a video tutorial on this topic and they seem to have no problems, but I do. (Video Link: https://laracasts.com/series/learn-vue-2-step-by-step/episodes/26)
To clarify, the error did not occur until I added <router-view></router-view> to index.html (Line Link: https://github.com/kernelcurry/httpverbs-site/blob/c56ba0a45445f7d28c31cb6928471da3619a3327/index.html#L10)
I wish I could give more insight into that is going on here, but I am at a loss. Thanks to anyone willing to look at the code and point me in the correct direction :)
Change your src/routes.js as follows:
import VueRouter from 'vue-router';
import Home from './views/home.vue'
import About from './views/about.vue'
let routes = [
{
path: '/',
component: Home
},
{
path: '/about',
component: About
}
];
export default new VueRouter({
routes
});
I have the following routes variable defined in my app-routing.module.ts:
const routes: Routes =
[
{ path: '', redirectTo: '/users', pathMatch: 'full' },
{ path: 'users', component: UsersComponent },
{ path: 'dashboard', component: DashboardComponent }
];
With this current configuration, when I submit http://localhost:3000/users, the browser redirects to http://localhost:3000/users/users and then displays the user list binding in the html as expected.
However, something seems off kilter for the browser to redirect from /users to /users/users. If I remove the th first route config with the redirectTo attribute then the browser stays on /users without redirecting to /users/users. However, in this scenario, the user list binding doesn't display as expected.
Any idea what might be causing the redirect to /users/users? Any idea how I can keep the browser on /users and get the user list binding to properly display at this uri?
Option 1: Setting base tag
In order to get the router working properly a base href needs to be defined somehow for the app. The docs recommend adding a base element to the head of your index.html file, such as:
<base href="/">
Option 2: Setting a provider
This can be a bit dangerous however as it has (potentially unexpected) side effects on anchor tags, empty href tags, etc, etc. It also breaks inline svg sprites... which was a major part of our app's UI. If you want to make the router work but not break a lot of things you can actually define the base href elsewhere, like so:
// ... other imports
import { APP_BASE_HREF } from '#angular/common';
#NgModule({
// ... other pieces of ngModule
providers: [
{provide: APP_BASE_HREF, useValue : '/' }
],
// ... other pieces of ngModule
})
export class AppModule {
constructor() {}
}
As a basic example. It's a bit hard to find in the documentation but is a good workaround to get things going without messing with everything else.
I have an app that is structured like this.
<app>
<header>
<component-a></component-a>
</header>
<div>
<router-outlet></router-outlet>
<component-b></component-b> <!-- loaded through router -->
</div>
</app>
In component-b some data is retrieved and later set to a new object. For example, something like this..
{
infoThatComponentANeeds : true,
someMoreInfoAddedFromCompB : []
}
This info is needed for the template in component-a. At first I tried to pass the info up to component-a via #Outuput and eventEmitter using a custom event. But I was unable to get it to bubble up. I suspect that has to do with it being loaded through the router. So now I am trying to share the data between the two components using a shared service.
My Service So Far:
import {Injectable} from 'angular2/core';
#Injectable()
export class SharedService
{
public spec:Spec= null;
public getSpec()
{
return this.spec;
}
public setSpec(spec:Spec)
{
this.spec = spec;
}
}
This is how I am trying to use it in component-a:
ngDoCheck()
{
if(this._sharedService.spec)
{
this.spec= this._sharedService.getSpec();
}
}
The Problem:
After the spec is set in component-b and ngDoCheck from component-a checks to see if the spec has been set. It comes back as undefined so the getSpec() function does not run, and no spec is returned. So I am not sure what I am missing, or why it would still be undefined in my SharedService after it has been set. Should the shared service keep a reference to what was set? Or am I completely misunderstanding this concept?
I have also explored ways of sharing this data via promises/observables. However I have not had any luck with that either. And the majority of the examples I have found use HTTP, which I really do not need at this point.
Update:
Here is some more info.
Boot.ts
import {bootstrap} from 'angular2/platform/browser';
import {HTTP_PROVIDERS} from 'angular2/http';
import {
ROUTER_PROVIDERS,
APP_BASE_HREF,
Location,
LocationStrategy,
HashLocationStrategy,
PathLocationStrategy
} from 'angular2/router';
import {AppComponent} from './components/app.component';
import {SharedService} from './services/shared.service';
bootstrap(<any>AppComponent, [
ROUTER_PROVIDERS,
SharedService,
provide(LocationStrategy, {useClass: PathLocationStrategy})
]);
AppComponent.ts
import {AfterViewInit, Component, OnInit} from 'angular2/core';
import {RouteConfig, ROUTER_DIRECTIVES} from 'angular2/router';
import {ComponentA} from './componentA';
#Component({
selector : 'body',
directives : [ComponentA, ROUTER_DIRECTIVES],
template : `
<app>
<header>
<component-a></component-a>
</header>
<div>
<router-outlet></router-outlet>
</div>
</app>
`
})
#RouteConfig([
{path: '/:appName/', name: 'ComponentB', component: ComponentB}
])
export class AppComponent
{
constructor(){}
}
Update 2:
Here is a plunker I created to try to isolate the issue. I removed the router stuff and simplified the whole thing. I am still seeing the same result..
https://plnkr.co/edit/kx6FWWGS1i04bH5J9DXM?p=preview
Watch the console.log()
Fixed:
This was the key.
Be sure to remove configurations in the providers attribute of your
two components.
Perhaps your service isn't actually shared. I mean you could have two instances according to the way you configured providers.
To be sure, just add the service when bootstrapping your application:
bootstrap(AppComponent, [ SharedService ]);
Be sure to remove configurations in the providers attribute of your two components.
If you're interested in hierarchical injectors of Angular2 (the concept behind this), you could have a look at this question:
What's the best way to inject one service into another in angular 2 (Beta)?