Connect Angular routing with MVC routing - asp.net-mvc

In my new project in WebApi2 I use Angular2 framework. After configuring and adding angular I tried to call first compnent. And there is my question. How to connect angular routing with webapi2? I add new class where I add routing:
I call <home-page> in MVC controller view Index.cshtml
app.routing.ts
const appRoutes: Routes = [
{ path: 'home', component: HomePage },
{ path: 'test', component: AppComponent}
];
app.component.ts
#Component({
selector: 'my-app',
templateUrl: './app.template.html',
})
HomePage.component.ts
#Component({
selector: 'home-page',
templateUrl: './HomePage.template.html',
providers: [GetContent]
})
system.config.js
paths: {
// paths serve as alias
'npm:': 'node_modules/'
},
// map tells the System loader where to look for things
map: {
// our app is within the Angular folder
'app': 'Angular',
// angular bundles ...
}
meta: {
'./*.js': {
loader: '/systemjs-angular-loader.js'
}
}
shared _Layout.cshtml
<script src="/node_modules/core-js/client/shim.min.js"></script>
<script src="/node_modules/zone.js/dist/zone.js"></script>
<script src="/node_modules/systemjs/dist/system.src.js"></script>
<script src="/systemjs.config.js"></script>
<script>
System.import('Angular/main.js').catch(function (err) { console.error(err); });
</script>
I included it to app.module.ts to imports section. When I launch application I see information from my HomePage component but when I add route path /test, it redirects me to HomePage component. Where have I made a mistake?

Can you try edit your app.module into this:
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { RouterModule, Routes } from '#angular/router';
import { AppComponent } from './app.component';
import { HomePageComponent } from './home-page.component';
const appRoutes: Routes = [
{path: '', redirectTo: 'home', pathMatch: 'full'},
{ path: 'home', component: HomePageComponent },
{ path: 'test', component: AppComponent}
{path: '**', component: NotFoundComponent}
];
#NgModule({
declarations: [
AppComponent,HomePageComponent
],
imports: [
BrowserModule,
RouterModule.forRoot(appRoutes)
],
providers : [],
bootstrap: [AppComponent]
})
export class AppModule { }

I resolved problem. I called <home-page> in Index.cshtml and that view was rendered from _Layout.cshtml. When I moved called component to _Layout.cshtml all things go correct. Thanks for help!

Related

Why my Angular 7 app doesn't render anything in the root route when I setup lazy loading?

I have implemented lazy loading in my app and since then, the root route is not working. I have read some posts and apparently it doesn't work in Angular 7 with lazy loading, I should redirect from "" to "whatever". The point is that it doesn't do the redirection, so my HomeComponent is never rendered. I have tried redirecting from other routes to the root route and it does the redirection, but it still doesn't render anything. Antoher thing I have tried is to render my HomeComponent in another path, like "home", but I need something happening in the root route, either a redirection or a rendering. Here is my code, thanks in advance!
PS: The rest of the routes are working perfectly, is just this one I can't make it work. If I try to render any other module from my app it does the same (nothing) and those modules are working in other routes.
app-routing.module.ts
...
const routes: Routes = [
// Home
{ path: '', redirectTo: 'home', pathMatch: 'full' }, // Doesn't redirect
{ path: 'home', loadChildren: './views/home/home.module#HomeModule' },
... // But it renders when you type the route in the browser
]
home.module.ts
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { HomeComponent } from './home.component';
import { HomeRoutingModule } from './home-routing.module';
#NgModule({
declarations: [HomeComponent],
imports: [
CommonModule,
HomeRoutingModule
]
})
export class HomeModule { }
home-routing.module.ts
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { HomeComponent } from './home.component';
const routes: Routes = [
{path: '', component: HomeComponent }
];
#NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class HomeRoutingModule { }
Remove exports: [RouterModule] from your HomeRoutingModule. you dont need export the router module in forChild routes modules. Only if you have a sub module with your forRoot routes. and you need import that module in your appModule (main module).

Angular routing redirect to that same page all time

I have problem with routing in my application. I use Angular2+ and WebApi2. I created Angular from quickstart project and I added it to my WebApi solution. After configurating it, I launched first time app allthing work fine. Problems appear after I added routing. When I try to navigate to link included in routing table, the browser redirect me all time to one component. I searched how to deal with it but I didn't find anything. Below I present codes and file names:
RouteConfig.cs
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{*url}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
Share _Layout.cshtml
<script src="/node_modules/core-js/client/shim.min.js"></script>
<script src="/node_modules/zone.js/dist/zone.js"></script>
<script src="/node_modules/systemjs/dist/system.src.js"></script>
<script src="~/src/systemjs.config.js"></script>
<script>
System.import('./src/main.js').catch(function (err) { console.error(err); });
</script>
system.config.js
packages: {
app: {
defaultExtension: 'js',
meta: {
'./*.js': {
loader: '/src/systemjs-angular-loader.js'
}
}
},
rxjs: {
defaultExtension: 'js'
}
}
app.module.ts
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { RouterModule, Routes } from '#angular/router';
import { AppComponent } from './app.component';
import { HomePage } from './HomePage.component';
import { Test } from './Test.component';
import { HttpModule } from '#angular/http';
const appRoutes: Routes = [
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home', component: HomePage },
{ path: 'test', component: Test },
{ path: '**', component: HomePage }
];
#NgModule({
declarations: [
AppComponent, HomePage, Test
],
imports: [
BrowserModule,
HttpModule,
RouterModule.forRoot(appRoutes)
],
providers: [],
bootstrap: [HomePage]
})
export class AppModule { }
Index.cshtml
<home-page></home-page>
Answer: all problems are caused by #RenderBody(). When I moved <home-page></home-page> under #RenderBody() all is working fine.

unhandled Promise rejection: No base href set. Please provide a value for the APP_BASE_HREF token or add a base element to the document

i work on a angular 4 project as front end for an asp.net MVC and API in the same solution when i set my routes i get the above error.
my code as following
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { RouterModule, Routes } from '#angular/router';
import { DashboardComponent } from
'../../Components/dashboard/dashboard.component';
import { TraitComponent } from '../../Components/trait/trait.component';
const routes: Routes = [
{ path: ' ', redirectTo: '/dashboard', pathMatch: 'full' },
{ path: 'dashboard', component:DashboardComponent },
{ path: 'Trait', component: TraitComponent },
//{ path: 'heroes', component: }
];
#NgModule({
imports: [
RouterModule.forRoot(routes) ,
CommonModule
],
exports: [RouterModule],
})
export class MyAppRoutingModuleModule {
i register/import the "myapprouting "and in my appmodule
that is code in my appComponent
<nav>
<a routerLink="localhost:56800/dashboard">Dashboard</a>
<a routerLink="localhost:56800/Trait">Heroes</a>
</nav>
<!-- <app-trait></app-trait>-->
<router-outlet>
</router-outlet>
In your app.module.ts, add the following :
{provide: APP_BASE_HREF, useValue: '/'}
to your **providers : [ ] ** so it would be like this :
providers: [{provide: APP_BASE_HREF, useValue: '/'},SomeService,AnotherService]
app.module.ts
import { APP_BASE_HREF } from '#angular/common'; <-- add those ***
const appRoutes: Routes = [
{ path: 'secondpage', component: SecondPageComponent },
];
#NgModule({
declarations: [
AppComponent,
NameEditorComponent,
ProfileEditorComponent,
SecondPageComponent
],
imports: [
BrowserModule,
// other imports ...
ReactiveFormsModule,
RouterModule.forRoot(
appRoutes,
{ enableTracing: true } //
)
],
providers: [{provide: APP_BASE_HREF, useValue: '/'}], <-- add those **** bootstrap: [AppComponent]
})
export class AppModule { }
Try to change the routerLink to this :
[routerLink]="['/dashboard']
[routerLink]="['/Trait']

Angular 2 routing not working with ASP.net core MVC

i'm working in an ASP.NET Core Web Application, using Angular 2 and VS 2015 as IDE. This is totally new for me, so i've been following every tutorial to get this page work. When i finally put everything together i face a routing problem: The page stays in the loading... tag and never show the content in the ModuleViewComponent. Read a lot of stackoverflow questions but I could not fix it.
My main.ts file looks like this:
// main entry point
import { platformBrowserDynamic } from '#angular/platform-browser-dynamic';
import { AppModule } from './app.module';
platformBrowserDynamic().bootstrapModule(AppModule);
the app.module.ts
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { FormsModule } from '#angular/forms';
import { HttpModule } from '#angular/http';
import { RouterModule, Routes } from '#angular/router';
import { NgForm } from '#angular/forms';
import { AppComponent } from './app.component';
import { ModuleViewComponent } from './components/CommonComponents/moduleView.component/moduleView.component';
const myRoutes: Routes = [
{
path: 'home',
component: ModuleViewComponent
},
{
path: '/',
redirectTo: 'home',
pathMatch: 'full'
}
];
#NgModule({
imports: [
RouterModule.forRoot(myRoutes),
BrowserModule,
FormsModule,
HttpModule
],
declarations: [
AppComponent,
NavbarComponent,
ModuleViewComponent
],
bootstrap: [AppComponent]
})
export class AppModule { }
app.component.ts
import { Component } from '#angular/core';
#Component({
selector: 'my-app',
template:'<router-outlet></router-outlet>'
})
export class AppComponent {
}
And the index.cshtml
#{
ViewData["Title"] = "Home Page";
}
<my-app>loading...</my-app>
How can i get this to work and show the component content? Any help is more than welcome, thanks in advance.
I have created a sample application which explains step by step details to create angular (Angular v4) applications with Asp.net MVC framework. Below is the link. Hope this helps you. You have to update route config file in your project so that angular can receive requests.
http://hive.rinoy.in/angular4-and-asp-net-mvc-hybrid-application/
http://hive.rinoy.in/routing-in-angular-asp-net-mvc-application/

Render angular2 Component on ASP.NET 5 MVC view with Routes

I am working on a ASP.NET MVC application that has several views that are serviced by a single Controller. The path of one of them is 'home/settings' and looks like this
With Angular2, I created a UserProfileComponent that basically renders a table containing list of the existing users and I would like it to render below User Profiles in the screenshot above:
user-profiles.component.ts
import { Component, Input } from '#angular/core';
import { UserService } from "../../services/userService";
#Component({
selector: 'user-profiles',
providers: [UserService],
template: `
...
`
})
export class UserProfilesComponent {
constructor(userService: UserService) {
userService.getUsers()
.subscribe(
users => this.users = users,
error => console.error('Error: ' + error),
() => console.log('Completedsfsdf!')
);
}
users = [];
}
Using Routing, I managed to render the UserProfileComponent when the settings view is rendered, but it only renders inside the tag inside the AppComponent template and I would like it to render inside my selector inside the settings view. It is also worth noting that the AppComponent is currently rendering inside the _Layout
app.ts
import { Component } from '#angular/core';
import { UserService } from './services/userService';
#Component({
selector: 'my-app',
providers: [UserService],
template: `
<p>Angular 2 is running...</p>
<!-- Routed views go here -->
<router-outlet></router-outlet>
`
})
export class AppComponent {
}
Which causes the table to render only at a layout level (on top of the page) instead on the inside the settings view.
boot.ts
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { AppComponent } from './app';
import { UserProfilesComponent } from './components/settings/user- profiles.component';
import { HomeComponent } from './components/home/home.component';
import { HttpModule } from '#angular/http';
import {UserService} from './services/userService'
import {APP_BASE_HREF} from '#angular/common';
import { RouterModule, Routes } from '#angular/router';
const appRoutes: Routes = [
{
path: 'home/settings',
component: UserProfilesComponent
},
{ path: '', component: HomeComponent }
];
#NgModule({
imports: [BrowserModule, HttpModule, RouterModule.forRoot(appRoutes)],
declarations: [AppComponent, HomeComponent, UserProfilesComponent],
providers: [{ provide: APP_BASE_HREF, useValue: '/' }],
bootstrap: [AppComponent]
})
export class AppModule { }
My initial approach here is have each section within the settings view to have its own component, so ideally RecordRollover will have its own component and so on. Is this possible?

Resources