微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript-如何在Angular应用程序范围之外更改Angular中的路由?

我的问题标题可能会有些混乱,因此希望以下详细信息可以解决它.
从本质上讲,导航栏是我无法控制的,仅以纯HTML / JS编写.我的应用程序是用Angular编写的,并且在其中设置了路由.

我可以做些什么来从导航栏触发Angular应用程序中的路由吗?

说我在index.html中具有以下内容

<body>
    <header>
        <a onclick="history.pushState({}, '', '/home');">Home</a>
        <a onclick="history.pushState({}, '', '/test');">Test</a>
    </header>
    <app-root></app-root>
</body>

显然,我的Angular应用程序是从< app-root>并且不知道其上方的标签.但是,是否有一种方法可以从Angular外部影响Angular内部的布线?

我认为调用history.pushState()可以更改它,但是它似乎没有任何作用.它的确更改了URL,但是浏览器上显示的组件保持不变.它不会切换组件.

有谁能解决这个问题?
我非常感谢您的帮助!

解决方法:

如果有人正在寻找潜在的解决方案,那么这是我在另一个论坛中推荐的解决方案.也许有一种更好的方法可以进行改进并加以改进,但这是我到目前为止所拥有的:

在app.component.ts中(或您要处理路由的任何地方):

declare var window: any;

//@Component stuff...
export class AppComponent implements OnInit, OnDestroy {

    routerSubject: Subject<string> = new Subject<string>();

    constructor(private router: Router) {
        // Assign the observable to the window object, so that we can call it from outside
        window.routerSubject = this.routerSubject;
    }

    ngOnInit() {
        this.routerSubject.subscribe((url: string) => {
            // Programmatically navigate whenever a new url gets emitted.
            this.router.navigate([`/${url}`]);
        });
    }

    ngOnDestroy() {
        this.routerSubject.unsubscribe();
    }
}

现在,在index.html中:

<body>
    <header>
        <!-- Emit a new value on click, so that Angular (which has already been subscribed) can programmatically route -->
        <a onclick="window.routerSubject.next('home');">Home</a>
        <a onclick="window.routerSubject.next('about');">About</a>
    </header>
    <app-root></app-root>
</body>

显然,您可以将onclick方法放在单独的JS文件中,并将Angular路由逻辑放在服务中,等等.但这是我想出的解决方案的主要内容.

无论哪种方式,这都应该使人们能够从外部路由Angular应用.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐