Angular 4 路由器:显示无重定向的视图

Angular 4 Router: show view without redirect

在带有 UI-Router 的 AngularJs 中,我可以执行以下操作以将任何未经授权或不存在的状态显示为特定视图,而无需重定向,以便用户可以知道route/url 失败的是什么:

.state('notauthorized', {
    templateUrl: 'notauthorized.html'
})
.state('notfound', {
    templateUrl: 'notfound.html'
});

现在我正在使用内置的 RouteModule 开发 Angular 4。有什么方法可以在不将用户重定向到完全不同的路径的情况下完成相同的任务吗??

太久没用过UI-Router,不记得它是怎么工作的,所以这可能不是你描述的。

但是对于 Angular,每个模板都有一个组件。因此,您的 "notauthorized" 和 "notfound" 模板需要一个组件。或者,您可以使用一个显示文本定义 "not authorized" 或 "not found".

的模板来完成一个组件

例如,我的页面未找到组件如下所示:

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

@Component({
    template: `
    <h1>This is not the page you were looking for!</h1>
    `
})
export class PageNotFoundComponent { }

您可以像这样更通用化:

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

@Component({
    template: `
    <h1>{{message}}</h1>
    `
})
export class MessageComponent {
    message: string;

}

这是否支持您的场景?

要在重新路由之前保留用户的 "current" 路由,您可以构建这样的服务:

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

@Injectable()
export class MessageService {
    currentUrl: string;

}

然后,当某处出现问题时,您将得到如下代码:

    this.messageService.currentUrl = url;
    this.router.navigate(['/pageNotFound']);

然后您可以检索 currentUrl 以显示它或其他任何内容。

我不知道这是否可行,但您始终可以重定向到 'not found' 视图,但告诉路由器不要更改 URL,这样在用户看来他们仍然在同一页/URL。

使用此处的 skipLocationChange 选项https://angular.io/api/router/NavigationExtras

在组件中:

 router.navigateByUrl("/pathToYourNotFoundView", { skipLocationChange: true });

或者如果它是模板中的 link -

<a [routerLink]="..." skipLocationChange>click me</a>