-->

Routing through links in Angular2

2019-08-24 02:30发布

问题:

I am new in Angular 2 and I am still in learning phase, but I stuck in a problem and not getting the solution to it. Please help.

I have made a view of a login, then a link to it after clicking the link it will redirect to home then clicking a link there it will redirect to some other view.

Below is my code structure:

app.routing.ts:

import { Routes } from '@angular/router';
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { LoginComponent } from './login/login.component';
import { UsersComponent } from './users/usercomponent';

export const routes: Routes = [
    { path: 'Home', component: HomeComponent },
    { path: 'Login', component: LoginComponent },
    { path: 'User', component: UsersComponent },

];

app.module.ts:

import { FormsModule } from '@angular/forms';

import { routes } from './app.routing';
import { LoginComponent } from './login/login.component';
import { HomeComponent } from './home/home.component';
import { UsersComponent } from './users/usercomponent';

@NgModule({
    imports: [BrowserModule, FormsModule, RouterModule.forRoot(routes)],
    declarations: [AppComponent, LoginComponent, HomeComponent, UsersComponent],
    bootstrap: [AppComponent]
})
export class AppModule { } 

app.component.ts:

import { Component } from '@angular/core';
import { OnInit } from '@angular/core';

@Component({
    selector: 'app-initializer',
    templateUrl: './app.component.html'

})


export class AppComponent {
    title = 'Some NAme'
} 

app.component.html:

<a routerLink="Login">Login</a>
<br />
<div>
    <router-outlet></router-outlet>
</div>

login.component.ts:

import { Component } from '@angular/core';

@Component({
    selector: 'login',
    template: `
    <h1><a routerLink="Home">Home</a>
<a routerLink="User">Users</a></h1>
<div>
    <router-outlet></router-outlet>
</div>
  `
})
export class LoginComponent {
    constructor() {

    }
}

The first page is working but after clicking home it is giving an error:

Cannot match any routes. URL Segment: 'Login/Home

I know that the link will be like / login, /home etc not like /login/home but how to implement it as I am not getting the solution for it and I am completely new to it.

回答1:

Instead of giving only <h1><a routerLink="Home">Home</a> you need to add / before the link like <h1><a routerLink="/Home">Home</a>.