하위 경로에서 상위 경로로 어떻게 이동합니까?
내 문제는 아주 고전적입니다. 나는 뒤에있는 응용 프로그램의 비공개 부분이 login form
있습니다. 로그인이 성공하면 관리 응용 프로그램의 하위 경로로 이동합니다.
내 문제는 global navigation menu
라우터가 내 AdminComponent
.NET 대신 내 라우팅을 시도하기 때문에을 사용할 수 없다는 것입니다 AppCompoment
. 그래서 내 탐색이 깨졌습니다.
또 다른 문제는 누군가가 URL에 직접 액세스하려는 경우 상위 "로그인"경로로 리디렉션하고 싶다는 것입니다. 그러나 나는 그것을 작동시킬 수 없습니다. 이 두 가지 문제가 비슷한 것 같습니다.
어떻게 할 수 있는지 아십니까?
링크 / HTML을 원하시나요? 아니면 명령 적 / 코드로 라우팅 하시겠습니까?
Link : RouterLink 지시문은 항상 제공된 링크를 현재 URL에 대한 델타로 취급합니다.
[routerLink]="['/absolute']"
[routerLink]="['../../parent']"
[routerLink]="['../sibling']"
[routerLink]="['./child']" // or
[routerLink]="['child']"
// with route param ../../parent;abc=xyz
[routerLink]="['../../parent', {abc: 'xyz'}]"
// with query param and fragment ../../parent?p1=value1&p2=v2#frag
[routerLink]="['../../parent']" [queryParams]="{p1: 'value', p2: 'v2'}" fragment="frag"
RouterLink를 사용하면 directives
어레이 를 가져 와서 사용해야합니다 .
import { ROUTER_DIRECTIVES } from '@angular/router';
@Component({
directives: [ROUTER_DIRECTIVES],
명령형 :이 navigate()
방법에는 시작점 (즉, relativeTo
매개 변수)이 필요합니다. 제공되지 않는 경우 탐색은 절대적입니다.
import { Router, ActivatedRoute } from '@angular/router';
...
constructor(private router: Router, private route: ActivatedRoute) {}
...
this.router.navigate(["/absolute/path"]);
this.router.navigate(["../../parent"], {relativeTo: this.route});
this.router.navigate(["../sibling"], {relativeTo: this.route});
this.router.navigate(["./child"], {relativeTo: this.route}); // or
this.router.navigate(["child"], {relativeTo: this.route});
// with route param ../../parent;abc=xyz
this.router.navigate(["../../parent", {abc: 'xyz'}], {relativeTo: this.route});
// with query param and fragment ../../parent?p1=value1&p2=v2#frag
this.router.navigate(["../../parent"], {relativeTo: this.route,
queryParams: {p1: 'value', p2: 'v2'}, fragment: 'frag'});
// navigate without updating the URL
this.router.navigate(["../../parent"], {relativeTo: this.route, skipLocationChange: true});
이것은 2017 년 봄부터 저에게 효과가있는 것 같습니다.
goBack(): void {
this.router.navigate(['../'], { relativeTo: this.route });
}
컴포넌트 ctor가 수락 ActivatedRoute
하고 Router
다음과 같이 가져 오는 위치 :
import { ActivatedRoute, Router } from '@angular/router';
다음과 같이 부모 루트로 이동할 수 있습니다.
this.router.navigate(['.'], { relativeTo: this.activeRoute.parent });
생성자에 현재 활성 경로를 삽입해야합니다.
constructor(
private router: Router,
private activeRoute: ActivatedRoute) {
}
현재 경로 또는 상위 경로의 매개 변수 수에 관계없이 상위 구성 요소로 이동하려면 Angular 6 업데이트 1/21/19
let routerLink = this._aRoute.parent.snapshot.pathFromRoot
.map((s) => s.url)
.reduce((a, e) => {
//Do NOT add last path!
if (a.length + e.length !== this._aRoute.parent.snapshot.pathFromRoot.length) {
return a.concat(e);
}
return a;
})
.map((s) => s.path);
this._router.navigate(routerLink);
이것은 싱글 톤 라우터와 함께 사용할 수있는 절대 경로라는 추가 보너스가 있습니다.
(Angular 4+, 아마도 Angular 2도 가능합니다.)
constructor(private router: Router) {}
navigateOnParent() {
this.router.navigate(['../some-path-on-parent']);
}
라우터는
- absolute paths
/xxx
- started on the router of the root component - relative paths
xxx
- started on the router of the current component - relative paths
../xxx
- started on the parent router of the current component
add Location to your constructor from @angular/common
constructor(private _location: Location) {}
add the back function:
back() {
this._location.back();
}
and then in your view:
<button class="btn" (click)="back()">Back</button>
Another way could be like this
this._router.navigateByUrl(this._router.url.substr(0, this._router.url.lastIndexOf('/'))); // go to parent URL
and here is the constructor
constructor(
private _activatedRoute: ActivatedRoute,
private _router: Router
) { }
My routes have a pattern like this:
- user/edit/1 -> Edit
- user/create/0 -> Create
- user/ -> List
When i am on Edit page, for example, and i need go back to list page, i will return 2 levels up on the route.
Thinking about that, i created my method with a "level" parameter.
goBack(level: number = 1) {
let commands = '../';
this.router.navigate([commands.repeat(level)], { relativeTo: this.route });
}
So, to go from edit to list i call the method like that:
this.goBack(2);
참고URL : https://stackoverflow.com/questions/37196882/how-do-i-navigate-to-a-parent-route-from-a-child-route
'Program Tip' 카테고리의 다른 글
''로 문장을 분할하고 주변 공백을 제거합니다. (0) | 2020.11.29 |
---|---|
정수 배열을 자바 스크립트의 문자열 배열로 변환 (0) | 2020.11.29 |
`vi`의 선택 항목 내에서 찾기 및 바꾸기 (0) | 2020.11.29 |
모든 줄 바꿈을 제거하고 특정 텍스트 뒤에 추가 (0) | 2020.11.29 |
Eclipse에서 Maven 프로젝트를 만들면 "Could not resolve archetype"이 표시됩니다. (0) | 2020.11.29 |