我创建了一个小服务,可以在其中存储路线更改。
import { Injectable } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
@Injectable()
export class RouteState {
private previousUrl: string;
private currentUrl: string;
constructor(private router: Router) {
this.currentUrl = this.router.url;
router.events.subscribe(event => {
if (event instanceof NavigationEnd) {
this.previousUrl = this.currentUrl;
this.currentUrl = event.url;
};
});
}
public getPreviousUrl() {
return this.previousUrl;
}
}
Run Code Online (Sandbox Code Playgroud)
但是每次路由更改时,vars currentUrl和previousUrl都是未定义的。难道我做错了什么?