Problem
I have 4 static pages with full angular 6 web app I want to render home.html page on start and after login redirect to actual angular web app from where angular routing fired up and do the magic. question is why I want this? I want this because my web app have some static pages like home, contact us,I want terms and conditions and privacy policy etc. I want this pages to be static for crawler friendly and also for fast rendering by excluding angular out of it.
Question
How I can achieve this.
Done so far
I create 3 static pages in root where index.html is located. the in angular cli I put this line
"index": "src/home.html",
but now I an unable to navigate to contactus.html page it shows me this error.
Error
"The selector "app-root" did not match any elements"
If I understand you right, you can use "Routes" for mapping your page and show in the same "index" all your contend easily. Is versatile, because with that, you can manage lot of things like the session access: I show you an example:
app.module.ts
import { Routes, RouterModule } from '#angular/router';
/*Example component*/
import { InicioComponent } from './inicio/inicio.component';
import{ ExamplePage } from './page1/examplePage.component';
/*Routes mapping*/
const routes: Routes = [
{path: '', component: InicioComponent },
{path: 'proveedores', component: ExamplePage, canActivate: [GuardService] }] /* Example of protected by session page*/
#NgModule({
declarations: [
ExamplePage,
InicioComponent
],
imports: [
RouterModule.forRoot(routes)
]
app.component.html
<h1>Angular</h1>
<hr>
<hr>
<app-header></app-header>
<div class="container text-center">
<router-outlet>**Here are all the pages**</router-outlet>
</div>
This is only a short example, is complicated do a deep explain of that here, but there are a lot of documentation in angular.io about this module: https://angular.io/guide/router
Related
I have an Angular 7 application, running .Net Core on the back end.
I have the following routes defined:
const routes: Routes = [
{ path: 'home', component: HomeComponent },
{ path: 'login', component: LoginComponent },
{ path: 'about', component: AboutComponent },
{ path: '**', redirectTo: 'home' }
];
In Visual Studio 2019, this is running at https://localhost:44358.
All works as expected.
But now I want to get metadata for a SAML implementation using sustainsys.saml2.aspnetcore2.
To get the metadata file, I try to enter https://localhost:44358/Saml2/ in my browser.
As expected, because the path does not match anything defined, the default route takes over and I am routed to the home page.
I removed the final path, so I no longer had any default routing for unmatched paths, and then it worked fine to get the metadata.
My question is: Is there any way to redirect to 'home' for all unmatched paths except some configured path (or paths), which would just be ignored as if the default route were not present?
Rather add a path to your base-href in index.html (e.g. <base href="/app/"/>) so that the Angular Router won't pick up paths on your root, then you'll be able to keep your wildcard redirect as is and /Saml2/ won't be intercepted.
Of course, if the app is already in production and you need to preserve URLs, you might not be in a position to make this kind of change.
I had created one project for login form, here am attaching screenshot of program,
while am executing my project it is showing only index page and waited for some time but still showing only index page, here am attaching output screenshot,
If you want to display a login page as a default page when user serves the application then you have to configure your app.module.ts to handle these type of URL. So the changes that you required is as:
In app.module.ts:
Import RouterModule from angular/router:
import { RouterModule } from '#angular/router';
and in imports Array add
RouterModule.forRoot([
{ path: '', redirectTo: '/login', pathMatch: 'full' },
{ path: 'login', component: LoginComponent }
])
and in app.component.html:
<router-outlet></router-outlet>
That’s because when we run ng-serve to start up our server it creates JavaScript bundles and automatically adds the right imports into our index.html.
In order for your app.component.html to show in localhost:4200, add <router-outlet></router-outlet? to your index.html.
Im trying to redirect my page from login to another page. Im following this code.
My login component ts file:
import { Router } from '#angular/router';
constructor(private router: Router) {
}
funLogin(mobilenumber){
this.router.navigateByUrl('registration');
}
In my html Im calling this function in a submit btn,
<button class="common-btn btn" (click)="funLogin(mobileNo.value)">Submit</button>
In my app.login.routing file,
export const loginRouting: Routes = [
{
path: '', component: DashboardRootComponent, canActivateChild: [],
children: [
{ path: '', component: DashboardComponent, pathMatch: 'full' },
{ path: 'home', component: HomeComponent },
{ path: 'registration', component: RegistrationComponent },
]
}
]
I have tried with "this.router.navigate" & referredlot of links. But it didnt work. Can anyone please tell me where Im going wrong or if you could give me a workingh sample it would be better.
#sasi.. try like this,
<a routerLink="/registration"><button class="btn btn-success" > Submit </button></a>
Update :
In order to use the routing in your application, you must register the components which allows the angular router to render the view.
We need register our components in App Module or any Feature Module of it (your current working module) in order to route to specific component view.
We can register components in two ways
.forRoot(appRoutes) for app level component registration like
featuteModules(ex. UserManagement) and components which you want register at root level.
.forChild(featureRoutes) for feature modules child components(Ex. UserDelete, UserUpdate).
you can register something like below,
const appRoutes: Routes = [
{ path: 'user', loadChildren: './user/user.module#UserModule' },
{ path: 'heroes', component: HeroListComponent },
];
#NgModule({
imports: [
BrowserModule,
FormsModule,
RouterModule.forRoot(
appRoutes
)
],
P.S : In order to navigate from one component to another, you must include the RouterModule in corresponding Module Imports array from #angular/router package.
You can navigate one to another page in Angular in Two ways. (both are same at wrapper level but the implementation from our side bit diff so.)
routerLink directive
routerLink directive gives you absolute path match like navigateByUrl() of Router class.
<a [routerLink]=['/registration']><button class="btn btn-success" > Submit </button></a>
If you use dynamic values to generate the link, you can pass an array of path segments, followed by the params for each segment.
For instance routerLink=['/team', teamId, 'user', userName, {details: true}] means that we want to generate a link to /team/11/user/bob;details=true.
There are some useful points to be remembered when we are using routerLink.
If the first segment begins with /, the router will look up the route
from the root of the app.
If the first segment begins with ./, or doesn't begin with a slash,
the router will instead look in the children of the current activated
route.
And if the first segment begins with ../, the router will go up one
level.
for more info have look here.. routerLink
Router class
We need inject Router class into the component in order to use it's methods.
There more than two methods to navigate like navigate() , navigateByUrl(), and some other.. but we will mostly use these two.
navigate() :
Navigate based on the provided array of commands and a starting point. If no starting route is provided, the navigation is absolute.
this.route.navigate(['/team/113/user/ganesh']);
navigate() command will append the latest string is append to existing URL. We can also parse the queryParams from this method like below,
this.router.navigate(['/team/'], {
queryParams: { userId: this.userId, userName: this.userName }
});
You can get the these values with ActivatedRoute in navigated Component. you can check here more about paramMap, snapshot(no-observable alternative).
navigateByUrl()
Navigate based on the provided URL, which must be absolute.
this.route.navigateByUrl(['/team/113/user/ganesh']);
navigateByUrl() is similar to changing the location bar directly–we are providing the whole new URL.
I am using angular 7 and I solved it in this way into my project.
1.First We need to implement this Modules to our app.module.ts file
import { AppRoutingModule} from './app-routing.module';
import { BrowserModule } from '#angular/platform-browser';
import { FormsModule } from '#angular/forms';
#NgModule({
imports: [
BrowserModule,
AppRoutingModule,
FormsModule,
],
})
2.Then Open your.component.html file and then fire a method for navigate where you want to go
<button class="btn btn-primary" (click)="gotoHome()">Home</button>
3.Then Go your.component.ts file for where you want to navigate. And add this code there.
import { Router } from '#angular/router';
export class YourComponentClassName implements OnInit {
constructor(private router: Router) {}
gotoHome(){
this.router.navigate(['/home']); // define your component where you want to go
}
}
4.And lastly want to say be careful to look after your app-routing.module.ts
where you must have that component path where you want to navigate otherwise it will give you error. For my case.
const routes: Routes = [
{ path:'', component:LoginComponent},
{ path: 'home', component:HomeComponent }, // you must add your component here
{ path: '**', component:PageNotFoundComponent }
];
Thanks I think, I share all of the case for this routing section. Happy Coding !!!
navigateByUrl expects an absolute path, so a leading / might take you to the right page
You could also use navigate and don't need the leading / but the syntax is slightly different as it expects an array for the path
https://angular.io/api/router/Router#navigateByUrl
<a class="nav-link mt-1" [routerLink]="['/login']"><i class="fa fa-sign-in"></i> Login</a>
Hi I am developing web application in Angular 5. I am trying to read appsettings.json and use the value in app.module.ts. In app.module.ts inside imports I have following line of code.
AppInsightsModule.forRoot('dfd77fnd-3ba9-43e6-a90f-3e762444938b')
In the above code value is hard coded. I have below tag in appsettings.json.
"ApplicationInsights": {
"InstrumentationKey": "dfd77fnd-3ba9-43e6-a90f-3e762444938b"
}
I want to read from appsettings.json. Below the app.module.ts I can read it. I have created service and inject it. App.module.ts the root file in Angular. Here how can i take the value from appsettings.json? Can someone help me to identify the solution for this? Any help would be appreciated. Thank you.
For loading the configuration data before application load you can use angular provided APP_INITIALIZER.
Details at :- https://devblog.dymel.pl/2017/10/17/angular-preload/
https://www.intertech.com/Blog/angular-4-tutorial-run-code-during-app-initialization/
providers: [
ConfigProvider,
{ provide: APP_INITIALIZER, useFactory: configProviderFactory, deps: [ConfigProvider], multi: true }
],
bootstrap: [AppComponent]
I am trying to use React Router from within react.rb. I started using the reactor-router Gem, but the Gem only works with React Router < 1 and I am using React Router 2.4.0 and the API is quite different.
Over the last weeks I have taken a few approaches to getting this working but none of the approaches have been correct, each having their own fault.
Please will someone steer me in the right direction as I am all out of options.
In terms of setup, I am using Webpack to require React and React Router so the application.js which is injected by Webpack looks like this:
React = require('react')
ReactDOM = require('react-dom')
_reactRouter = require('react-router')
Approach 1 - create the Router as native JS and call ReactDOM.render to render the router when rendering a top level component
before_mount do
#admin_members = React::API::create_native_react_class(Components::Company::AdminMember)
#squad_index = React::API::create_native_react_class(Components::Squad::Index)
#squad_show = React::API::create_native_react_class(Components::Squad::Show)
#tribe_index = React::API::create_native_react_class(Components::Tribe::Index)
#tribe_show = React::API::create_native_react_class(Components::Tribe::Show)
end
and then rendering the router to a div in after_mount:
after_mount do
`ReactDOM.render(React.createElement(
_reactRouter.Router,
{ history: _reactRouter.browserHistory },
React.createElement(_reactRouter.Route, { path: "admin/members", component: #{#admin_members} }),
React.createElement(_reactRouter.Route, { path: "/squads", component: #{#squad_index} }),
React.createElement(_reactRouter.Route, { path: "/squads/:squad_id", component: #{#squad_show} }),
React.createElement(_reactRouter.Route, { path: "/tribes", component: #{#tribe_index} }),
React.createElement(_reactRouter.Route, { path: "/tribes/:tribe_id", component: #{#tribe_show} })
), document.getElementById('bh_router_div')
);`
end
This approach, although not pretty, seems to work in that the Router is created and functions as expected. A URL or /tribe/22 will load the correct TribeShow component and will pass the correct ID to the component.
The problem I have with this approach is when it comes to creating a Link as the Link component does not share the same context as the router. I believe this is down to ReactDOM.render being called once by react-rb and then once again in the code above. This creates two root components on the page (TopLevelRailsComponent) and (ReactRouter).
The Link is created thus:
class MyRouter < React::NativeLibrary
imports '_reactRouter'
end
And then used in a components render method like this:
MyRouter.Link({to: "/admin/members"}) { "and here is the link"}
The link is rendered, but clicking on it gives the following warning and does not navigate to the component:
Uncaught TypeError: Cannot read property 'push' of undefined
Looking at the properties of the Link Component I see that context is null and I believe this is why. It seems the Link is being being drawn outside the context of the router.
Approach 2 - use the react-rb API to render the router so that ReactDOM.render is not being called twice on the page
This seems to be a better approach but so far I have not managed to get this to work properly.
Building on how I create the Link above, in the render method of a component:
MyRouter.Router({history: `_reactRouter.browserHistory` },
MyRouter.Route({ path: "/admin/members", component: #admin_members})
) {}
But I get the following warning and the page does not render:
Uncaught Invariant Violation: <Route> elements are for router configuration only and should not be rendered
Approach 3 - build the Route component in native JS so that it does not get rendered:
`var AppRoutes = React.createElement(_reactRouter.Route, { path: "/admin/members", component: #{#admin_members} });`
MyRouter.Router({history: `_reactRouter.browserHistory` },
`AppRoutes`
) {}
This gets past the previous error, BUT the router does not actually route and I get the following warning (and the component does not render):
Warning: [react-router] Location "/admin/members" did not match any routes
history: As a side note, in both the examples above, I have tried to set history as such:
MyRouter.Router({history: MyRouter.browserHistroy },
`AppRoutes`
) {}
But I get a warning about providing a depreciated history and when I check the value it is null. Using _reactRouter.browserHistorygets past this warning. I am not sure if this is relevant to this fact that the router is not routing or not.
I would really appreciate any help or steer on this. Even a steer as to which of the approaches is the correct and and any hints as to how to proceed would be very welcome indeed.
This has been addressed in the V2.4.0 branch of reactrb-router https://github.com/reactrb/reactrb-router/tree/v2-4-0
Also please note the new DSL