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

时间:2017-08-24 23:06:38

标签: angular angular-router

在使用UI-Router的AngularJs中,我可以执行以下操作,使任何未授权或不存在的状态显示特定视图而无需重定向,以便用户可以知道哪个路由/ URL是不成功的:

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

现在我正在使用内置的RouteModule处理Angular 4。有没有办法在不将用户重定向到完全不同的路线的情况下完成同样的工作?

2 个答案:

答案 0 :(得分:1)

我不知道是否可以,但您可以始终重定向到“未找到”视图,但告诉路由器不要更改URL,以便用户看到它们仍在同一页面/ URL上。

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

中的skipLocationChange选项

在组件中:

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

或者如果它是模板中的链接 -

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

答案 1 :(得分:0)

由于我已经使用过UI-Router,但我已经记不清它是如何工作的了,所以这可能不是你所描述的。

但是使用Angular,每个模板都有一个组件。因此,您需要一个适合您&#34;未经授权的组件&#34;和你的&#34; notfound&#34;模板。或者你可以使用一个模板做一个组件,该模板显示的文字定义为“未授权”和“#34;或&#34;未找到&#34;。

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

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;

}

这会支持您的方案吗?

保留用户&#34;当前&#34;在重新路由之前的路由,您可以构建这样的服务:

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

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

}

然后,当某个地方出现问题时,你会得到这样的代码:

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

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