javascript - 在 Angular 路由更改后调用 javascript 函数

标签 javascript angular

我在一个文件中有一个 javascript 函数,我路由到 Angular 项目中的 ng-view。路由完成后有没有办法执行上述功能?类似于 JavaScript 的 window.onload?

最佳答案

是的,你可以使用路由器事件, 在你的构造函数中,

    constructor(private router: Router) {
      this.router.events.subscribe(event => {
        if (event instanceof NavigationEnd) {
         // call your function here
        }
      });
    }

不要忘记导入

import { Router } from '@angular/router';

只有在导航即将结束时才会调用此事件。

**The sequence of router events is as follows,**
NavigationStart,
RouteConfigLoadStart,
RouteConfigLoadEnd,
RoutesRecognized,
GuardsCheckStart,
ChildActivationStart,
ActivationStart,
GuardsCheckEnd,
ResolveStart,
ResolveEnd,
ActivationEnd
ChildActivationEnd
NavigationEnd,
NavigationCancel,
NavigationError
Scroll

这是您可以查看 Angular 文档的所有导航事件 https://angular.io/api/router/Event

关于javascript - 在 Angular 路由更改后调用 javascript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59298963/

相关文章:

javascript - event.preventDefault() 不工作

javascript - 更新数据库对象中的特定字段 | Axios、Redux 形式

javascript - Angular 2 : How to prevent/nullify history manipulation while implementing routerCanDeactivate?

html - 如何使用 *ngFor 在 Angular 中显示数据行

Javascript 正则表达式和替换连续字符集

javascript - 无法读取未定义的不一致嵌入的属性 'includes' 来检测表情符号

Javascript 从 AJAX 响应中读取 JSON 结果

angular - 如何在 promise 之外使用变量

typescript - AngularJS 2 隐藏位置策略后退导航

javascript - Angular Material 6 Mat-Chip-List - 两个 mat-chip-list 声明共享相同的数据源