Маршрутизация Angular2: Страница не переходит к моему компоненту просмотра при нажатии на ссылку маршрутизатора

#angular #typescript #angular2-routing #angular2-template

#angular #машинописный текст #angular2-маршрутизация #angular2-template

Вопрос:

Я создал свои app.routes.ts и импортировал все соответствующие библиотеки.

После этого я связал все пути с их соответствующими компонентами следующим образом:

 import {ModuleWithProviders} from '@angular/core';
import {Routes, RouterModule} from '@angular/router';
import {AttendanceComponent} from './attendance/attendance.component';
import {LoginComponent} from './login/login.component';

//Route Configuration
export const routes: Routes = [
  {path: '', component: LoginComponent},
  {path: 'attendance', component: AttendanceComponent}
];

export const routing: ModuleWithProviders = RouterModule.forRoot(routes);
  

Я увеличил свое приложение в my app.module :

 import { Component, NgModule } from '@angular/core';
import { LocationStrategy, HashLocationStrategy } from '@angular/common';
import { BrowserModule } from '@angular/platform-browser';
import { RouterModule } from '@angular/router';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

//declarations
import { AppComponent } from './app.component';
import { LoginComponent } from  './login/login.component';
import { AttendanceComponent } from './attendance/attendance.component';
import { routing, routes } from './app.routes';

//decorator
@NgModule({
  imports:      [
      BrowserModule,
      FormsModule,
      HttpModule,
      routing,
      RouterModule
    ],
  declarations: [
        AppComponent,
        LoginComponent,
        AttendanceComponent
      ],
  //put services
  //providers: [{provide: LocationStrategy, useClass: HashLocationStrategy}],
  bootstrap: [ AppComponent ]
})
export class AppModule {
  //module class
}
  

На моем app.component я вызвал свою целевую страницу

 import {Component} from '@angular/core';
import {LoginComponent} from './login/login.component';

@Component({
  selector: 'oosc_app',
  template: `<login></login>`
})

export class AppComponent{
}
  

Целевая страница login.template.html :

 <body class="login">
<div id="login" class="login-position">
        <div class="logo">
            <a href="index.html"><img src="assets/images/oosc-logo-login.png" alt="" /></a>
        </div>

        <div class="wrapper-login">
            <input type="text" placeholder="TSC Number" class="user"/>
            <input type="password" placeholder="Password" class="password"/>
        </div>

        <!--<a [routerLink]="['/attendance']" class="login-button">Sign in</a>-->
        <a [routerLink]="['/attendance']"  class="login-button">Sign in</a>
        <router-outlet></router-outlet>
        <span>Not a member ?<a href="#">Create your account</a></span>
    </div>
</body>
  

Ссылка на маршрутизатор должна направлять страницу на attendance.component.ts последующее отображение представления.

Проблема в том, что при нажатии кнопки входа в систему она переходит к localhost: 3000 / посещаемость, но не привязывается к представлению входа вместо представления посещаемости.

Ниже мой attendance.component.ts :

 //I have separated it into headers and footers and called the templateUrl
//in a component called Content

import {Component} from '@angular/core';
import {OnInit} from '@angular/core';
import {HeaderComponent} from '../partials/header.component';
import {FooterComponent} from '../partials/footer.component';
import {ContentComponent} from '../partials/content.component';

@Component({
  selector: 'attendance',
  //templateUrl:  `/app/attendance/attendance.template.html`
  template: `<header></header><footer></footer>`,
  providers: [HeaderComponent, ContentComponent, FooterComponent]
})

export class AttendanceComponent implements OnInit{
  ngOnInit(){
    console.log('ngOnInit');
  }
}
  

В чем, по-видимому, проблема?

Почему он не переходит к соответствующему представлению?

Ответ №1:

Проблема в том, router-outlet что отсутствует в вашем шаблоне.

 template: `    
    <router-outlet></router-outlet>

    <!-- not required -->
        <login></login>      
    <!-- now you don't need to use <login> tag your router will load 
          login component into router-outlet because of your default defined path-->

`