하위 경로에서 상위 경로로 이동하려면 어떻게 해야 합니까?
제 문제는 꽤 고전적입니다.애플리케이션의 개인적인 부분이 있는데, 이 부분은 다음과 같습니다.login form
로그인이 성공하면 관리 응용 프로그램의 하위 경로로 이동합니다.
제 문제는 제가 그것을 사용할 수 없다는 것입니다.global navigation menu
라우터가 내 안에서 라우팅을 시도하기 때문입니다.AdminComponent
의 내것대에 AppCompoment
그래서 내비게이션이 고장났습니다.
또 다른 문제는 누군가 URL에 직접 액세스하려는 경우 부모 "로그인" 경로로 리디렉션하고 싶다는 것입니다.하지만 난 그것을 할 수 없어요.제가 보기에는 이 두 가지 문제가 비슷한 것 같습니다.
어떻게 할 수 있는지 아십니까?
링크/HTML을 원하십니까? 아니면 명령적으로/코드로 라우팅하시겠습니까?
링크: 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"
를 가져와 사용해야 .directives
매개 변수:
import { ROUTER_DIRECTIVES } from '@angular/router';
@Component({
directives: [ROUTER_DIRECTIVES],
필수:그navigate()
방법시즉점작은즉(점,▁requires법▁a시)을 합니다.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 });
}
가 성가요소허위용는치를 수락하는 ActivatedRoute
그리고.Router
다음과 같이 가져옵니다.
import { ActivatedRoute, Router } from '@angular/router';
다음과 같이 상위 루트로 이동할 수 있습니다.
this.router.navigate(['.'], { relativeTo: this.activeRoute.parent });
생성자에 현재 활성 경로를 주입해야 합니다.
constructor(
private router: Router,
private activeRoute: ActivatedRoute) {
}
constructor(private router: Router) {}
navigateOnParent() {
this.router.navigate(['../some-path-on-parent']);
}
라우터는 다음을 지원합니다.
- 경로 대 로 경절
/xxx
요소의 되었습니다. 루트 구성 요소: - 경로 대 로 경
xxx
요소의 되었습니다. 예를 들어 다음과 같습니다. - 경로 대 로 경
../xxx
요소의 되었습니다. 예를 들어 다음과 같습니다.
별 탈 없이:
this.router.navigate(['..'], {relativeTo: this.activeRoute, skipLocationChange: true});
매개 변수 '...'는 탐색을 한 단계 위로 만듭니다. 즉, 부모:
현재 경로 또는 상위 경로의 매개 변수 수에 관계없이 상위 구성 요소로 이동하려면 다음과 같이 하십시오.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);
이것은 싱글톤 라우터와 함께 사용할 수 있는 절대 경로라는 추가적인 이점이 있습니다.
(분명히 각도 4+, 아마도 각도 2도 마찬가지일 것입니다.)
다른 방법은 이렇게 될 수 있습니다.
this._router.navigateByUrl(this._router.url.substr(0, this._router.url.lastIndexOf('/'))); // go to parent URL
그리고 여기 건설자가 있습니다.
constructor(
private _activatedRoute: ActivatedRoute,
private _router: Router
) { }
내 경로에는 다음과 같은 패턴이 있습니다.
- user/edit/1 -> 편집
- user/create/0 -> Create
- user/ -> 리스트
예를 들어, 내가 편집 페이지에 있고 목록 페이지로 돌아가야 할 때, 나는 경로에서 2단계를 반환할 것입니다.
그런 생각을 하면서, 저는 "레벨" 매개변수로 제 방법을 만들었습니다.
goBack(level: number = 1) {
let commands = '../';
this.router.navigate([commands.repeat(level)], { relativeTo: this.route });
}
편집에서 목록으로 이동하려면 다음과 같이 메서드를 호출합니다.
this.goBack(2);
이 모든 것이 나에게 효과가 없었습니다...백 기능이 있는 내 코드는 다음과 같습니다.
import { Router } from '@angular/router';
...
constructor(private router: Router) {}
...
back() {
this.router.navigate([this.router.url.substring(0, this.router.url.lastIndexOf('/'))]);
}
this.router.url.substring(0, this.router.url.lastIndexOf('/') --> "/" --> 현재 경로 가져오기 후 현재 URL의 마지막 부분을 가져옵니다.
uiSref 지시문을 사용하는 경우 다음을 수행할 수 있습니다.
uiSref="^"
상대 경로를 사용할 것을 제안하는 모든 사람은 가장 중요한 부분에 대해 잊어버립니다. 상대 경로는 항상 경로에 있는 (가능한) 매개 변수에 따라 달라집니다.
예를 들어 자식 경로가 있는 경우edit/:id
그리고 당신의 ID는 다음과 같은 형식의 URI입니다./api/something/123
그런 다음 상대 경로를 사용하여 부모님께 가기 위해 사용해야 합니다.[../../../..']
즉, URL을 컴퓨터의 디렉터리 구조처럼 처리합니다.라우팅 테이블에 작성된 정의의 관점에서 경로를 생각하지 마십시오.
내 솔루션은 다음과(와)
const urlSplit = this._router.url.split('/');
this._router.navigate([urlSplit.splice(0, urlSplit.length - 1).join('/')], { relativeTo: this._route.parent });
그리고.Router
주입:
private readonly _router: Router
언급URL : https://stackoverflow.com/questions/37196882/how-do-i-navigate-to-a-parent-route-from-a-child-route
'programing' 카테고리의 다른 글
VB에서 동사 문자열 리터럴을 수행하는 방법.NET? (0) | 2023.05.07 |
---|---|
openpyxl 일반 워크북을 사용하여 열의 마지막 행을 찾는 방법은 무엇입니까? (0) | 2023.05.07 |
Postgres: bash 스크립트에서 다시 생성/재채우기 전에 전체 데이터베이스 지우기 (0) | 2023.05.07 |
Xcode 6/7/8에서 디버그 빌드와 릴리스 빌드를 전환하려면 어떻게 해야 합니까? (0) | 2023.05.07 |
인터페이스를 사용할 때 개인 설정기를 어떻게 구현합니까? (0) | 2023.05.07 |