使用角度路由时不会发生重定向

时间:2019-02-27 08:05:48

标签: html angular typescript

我创建了示例角度应用程序,并希望使用浏览器URL http://localhost:1800/demo定向到另一个页面。

index.html

<!doctype html>
<html lang="en">
<head>
    <title>Sample Angular app</title>
    <base href="/">
    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
    <app-root></app-root>
    <router-outlet></router-outlet>
</body>
</html>

以下是具有代码的主页(app.component.ts)

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

@Component ({
    selector: 'app-root',
    template: `<div class="sample-class">Sample text to test this sample angular app</div>`,
    styles: [] }) export class AppComponent {
    title = "Sample title"; };

以下是app-routing.module.ts

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { DemoComponent } from './demo/demo.component';

const routes: Routes = [
    //{ path: '', redirectTo: '/login' }
    { path: 'demo', component: DemoComponent }
]

@NgModule ({
    imports: [RouterModule.forRoot(routes)]
})

export class AppRoutingModule{};

我将demo.component.ts定义为

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

@Component ({
    selector: 'demo',
    template: `<div>Demo page</div>`,
    styles: []
})

export class DemoComponent {};

及其对应的模块为

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

import { DemoComponent } from './demo.component';

@NgModule ({
    declarations: [DemoComponent],
    exports: [DemoComponent],
    bootstrap: [DemoComponent]
})

export class DemoModule {};

app.component.html

<!--The content below is only a placeholder and can be replaced.-->
<div style="text-align:center">
    <h1>
        Welcome to {{title}}!
    </h1>
    <img width="300" src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNTAgMjUwIj4KICAgIDxwYXRoIGZpbGw9IiNERDAwMzEiIGQ9Ik0xMjUgMzBMMzEuOSA2My4ybDE0LjIgMTIzLjFMMTI1IDIzMGw3OC45LTQzLjcgMTQuMi0xMjMuMXoiIC8+CiAgICA8cGF0aCBmaWxsPSIjQzMwMDJGIiBkPSJNMTI1IDMwdjIyLjItLjFWMjMwbDc4LjktNDMuNyAxNC4yLTEyMy4xTDEyNSAzMHoiIC8+CiAgICA8cGF0aCAgZmlsbD0iI0ZGRkZGRiIgZD0iTTEyNSA1Mi4xTDY2LjggMTgyLjZoMjEuN2wxMS43LTI5LjJoNDkuNGwxMS43IDI5LjJIMTgzTDEyNSA1Mi4xem0xNyA4My4zaC0zNGwxNy00MC45IDE3IDQwLjl6IiAvPgogIDwvc3ZnPg==">
</div>
<h2>Here are some links to help you start: </h2>
<ul>
    <li>
        <h2><a target="_blank" rel="noopener" href="https://angular.io/tutorial">Tour of Heroes</a></h2>
    </li>
    <li>
        <h2><a target="_blank" rel="noopener" href="https://angular.io/cli">CLI Documentation</a></h2>
    </li>
    <li>
        <h2><a target="_blank" rel="noopener" href="https://blog.angular.io/">Angular blog</a></h2>
    </li>
</ul>
<router-outlet>
</router-outlet>

当尝试获取http://localhost:1800/demo时,其显示的主页相同,并且没有重定向发生。也没有显示错误。请帮助我解决此问题。

1 个答案:

答案 0 :(得分:3)

在您的AppRoutingModule中导出RouterModule。

exports: [RouterModule]

没有导出,Angular无法找到您的路由配置。

相关问题