Tes*_*dor 5 typescript angular angular7
我创建了一个小服务,可以在其中存储路线更改。
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都是未定义的。难道我做错了什么?
sid*_*hah 11
使用angular的位置服务,它内置于angular中,并从“ @ angular / common”导入,如下所示:
import { Component, OnInit, Input } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Location } from '@angular/common';
import { Hero } from '../hero';
import { HeroService } from '../hero.service';
@Component({
selector: 'app-hero-detail',
templateUrl: './hero-detail.component.html',
styleUrls: [ './hero-detail.component.css' ]
})
export class HeroDetailComponent implements OnInit {
@Input() hero: Hero;
constructor(
private location: Location
) {}
goBack() {
this.location.back();
}
}
Run Code Online (Sandbox Code Playgroud)
然后使用location.back()转到上一页。这是一个工作示例:
https://stackblitz.com/angular/qvvrbgrmmda
这是一种获取之前路线的方法@angular/router
在原始帖子中查找更多信息
import { Injectable } from '@angular/core';
import { Router, RouterEvent, NavigationEnd } from '@angular/router';
import { filter } from 'rxjs/operators';
@Injectable({
providedIn: "root"
})
export class PreviousRouteService {
private previousUrl: string;
private currentUrl: string;
constructor(private router: Router) {
this.currentUrl = this.router.url;
this.previousUrl = null;
this.router.events
.pipe(filter((event: RouterEvent) => event instanceof NavigationEnd))
.subscribe((event: NavigationEnd) => {
this.previousUrl = this.currentUrl;
this.currentUrl = event.urlAfterRedirects;
console.log("prev: ", this.previousUrl)
console.log("curr: ", this.currentUrl)
});
}
public getPreviousUrl() {
return this.previousUrl;
}
};
Run Code Online (Sandbox Code Playgroud)
如果你只想要以前的路线,你可以像这样创建一个 observable
get previousRoute$(): Observable<string> {
return this.router.events.pipe(
filter(e => e instanceof RoutesRecognized),
pairwise(),
map((e: [RoutesRecognized, RoutesRecognized]) => e[0].url)
);
}
Run Code Online (Sandbox Code Playgroud)
现在你可以订阅这个 observable 并执行任何操作(确保你在 OnDestroy 事件上取消订阅这个 observable。)
this.previousRoute$.subscribe(url => {
//perform your action
});
Run Code Online (Sandbox Code Playgroud)
注意:当用户处于第二次导航时,此 observable 将开始发出事件。
| 归档时间: |
|
| 查看次数: |
10457 次 |
| 最近记录: |