可以检查此路由是否返回有效页面?

时间:2018-02-21 21:39:16

标签: angular

我将Angular 5与localize-router一起使用。 Localize-router不支持没有语言前缀的路径(只有主页),所以我尝试编写组件来做到这一点。所以在路由器中我有2个组件:

{
    path: '404',
    component: NotFoundComponent,
},
{
    path: '**',
    component: NotFoundExceptionComponent
}

如果路线没有匹配任何路线,我将其推入NotFoundExceptionComponent我想要的地方 - 它应该重定向到另一个页面或404页面。

例如,当我有路径时: www.example.com/test 我想把它变成: www.excample.com/en/test 但如果有人写道: www.excample.com/testttt 要么 www.excample.com/en/testttt 我应该重定向到404页面。

我写了一个触发的方法:

public redirectIntoCorrectPath() {
    this.redirectUrl = this.localize.translateRoute(this.location.path()).toString();
}

但现在我需要检查 - this.redirectUrl是否有效或触发另一个NotFoundExceptionComponent操作。如果有效 - 重定向到此页面,如果无效,则重定向到404。

Angular中的任何方法都可以检测此URL重定向用户的位置吗?是**还是不?

现在我只有一个想法来创建单例并检测一个接一个的重定向是太快还是有一个共同的元素(一个包含在另一个中)然后将用户重定向到404,但我寻找更好的解决方案。

1 个答案:

答案 0 :(得分:0)

此时此问题对我来说与我的问题中的路由器配置一样。

public redirectIntoCorrectPath() {
    let control = false;

    // This function look for element in router & set control=true if element is found
    function controlUrlInRouter(obj, redirect) {
        try {
            obj.forEach(line => {
                if (!control) {
                    if (line.children) {
                        controlUrlInRouter(line.children, redirect);
                    } else {
                        if (line.path && line.path.length > 0 && redirect.indexOf(line.path) > -1) {
                            control = true;
                        }
                    }
                }
            });
        } catch (e) {
            console.log(e);
        }
    }

    if (this.localizeParser.getLocationLang(this.location.path())) {
        // If element has language in URL and is not found -> redirect them into /404
        this.router.navigate([this.localizeService.translateRoute('/404')]);
    } else {
        // If URL doesn't has any language in URL we need more investigation

        // Generate new URL from actual information
        this.redirectUrl = this.localizeService.translateRoute(this.location.path()).toString();

        // Test this new URL (in result we update control variable)
        controlUrlInRouter(this.router.config, this.redirectUrl);

        if (control) {
            // If we found any element in router, we redirect into this page
            this.router.navigate([this.redirectUrl]);
        } else {
            // If we doesn't found any element in router, we redirect into /404
            this.router.navigate([this.localizeService.translateRoute('/404')]);
        }
    }
}
相关问题