简体   繁体   中英

How to detect when route changed and new view replaced in Angular

I am looking to detect when route changed and new view(html) replaced.

Tried below code but don't know how to proceed further.

this._routerSub = this.router.events
  .filter(event => event instanceof NavigationEnd)
  //.do(event => console.log(event)) // 
  .subscribe((value) => { });

Also tried below code but getting error

Argument of type Event is not assignable to parameter of type '(value:Event)=>void'.

   import { Router, NavigationEnd, Event  } from '@angular/router';

   this._routerSub = this.router.events  
      .subscribe(event : Event) => {
      if (event instanceof NavigationEnd) {
        console.log(event.url);
      }
    });

Vega below are my app.component.ts and app.component.ts code. Isn't it suppose to call onActivate on activate. As router outlet will emit an activate event any time a new component is being instantiated.

app.component.html

<router-outlet (activate)="onActivate($event)" ></router-outlet>

app.component.ts

   onActivate(e) {
        debugger;
        console.log(1);
      }

How about using router-outlet exposed activate event:

<router-outlet (activate)="onActivate($event)"></router-outlet>

onActivate(e) {
  console.log(e.constructor.name);
  //etc... you can access to a lot of other information
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM