angular 2 라우터를 사용하여 현재 루트를 새로고침하는 방법
와 angular 2를 .hashlocation
★★★★★★ 。
컴포넌트는 다음 루트로 로드됩니다.
"departments/:id/employees"
아직까지는 괜찮아.
편집된 여러 테이블 행의 배치 저장을 정상적으로 수행한 후 다음을 통해 현재 루트 URL을 새로고침합니다.
this.router.navigate([`departments/${this.id}/employees`]);
하지만 아무 일도 일어나지 않아, 왜?
다음과 같이 예상되는 루트로 리다이렉트하는 함수를 컨트롤러에 만듭니다.
redirectTo(uri:string){
this.router.navigateByUrl('/', {skipLocationChange: true}).then(()=>
this.router.navigate([uri]));
}
그럼 이렇게 쓰세요.
this.redirectTo('//place your uri here');
이 함수는, 더미 루트로 리다이렉트 해, 유저 자신도 모르는 사이에 행선지 루트로 재빠르게 돌아옵니다.
은 이제 5.에서 Angular 5.1을 할 수 .onSameUrlNavigation
라우터 설정의 속성.
여기에 방법을 설명하는 블로그를 추가했지만 요지는 다음과 같습니다.
으로, 「」를 유효하게 합니다.onSameUrlNavigation
「」, 「」로 설정'reload'
이로 인해 이미 활성화되어 있는 루트로 이동하려고 하면 라우터가 이벤트사이클을 기동합니다
@ngModule({
imports: [RouterModule.forRoot(routes, {onSameUrlNavigation: 'reload'})],
exports: [RouterModule],
})
에서 " " " 를 설정합니다.runGuardsAndResolvers
로로 합니다.always
이것에 의해, 라우터는 항상 가드와 리졸바 사이클을 개시해, 관련 이벤트를 기동하도록 지시됩니다.
export const routes: Routes = [
{
path: 'invites',
component: InviteComponent,
children: [
{
path: '',
loadChildren: './pages/invites/invites.module#InvitesModule',
},
],
canActivate: [AuthenticationGuard],
runGuardsAndResolvers: 'always',
}
]
마지막으로 새로고침을 이노블로 하는 각 컴포넌트에서 이벤트를 처리해야 합니다.이를 수행하려면 라우터를 Import하여 이벤트에 바인드하고 컴포넌트 상태를 리셋하여 필요에 따라 데이터를 재취득하는 초기화 방식을 호출합니다.
export class InviteComponent implements OnInit, OnDestroy {
navigationSubscription;
constructor(
// … your declarations here
private router: Router,
) {
// subscribe to the router events. Store the subscription so we can
// unsubscribe later.
this.navigationSubscription = this.router.events.subscribe((e: any) => {
// If it is a NavigationEnd event re-initalise the component
if (e instanceof NavigationEnd) {
this.initialiseInvites();
}
});
}
initialiseInvites() {
// Set default values and re-fetch any data you need.
}
ngOnDestroy() {
if (this.navigationSubscription) {
this.navigationSubscription.unsubscribe();
}
}
}
이러한 순서를 모두 실시하면, 루트 새로고침을 유효하게 할 필요가 있습니다.
저는 Angular 11 프로젝트에 이것을 사용하고 있습니다.
reloadCurrentRoute() {
const currentUrl = this.router.url;
this.router.navigateByUrl('/', {skipLocationChange: true}).then(() => {
this.router.navigate([currentUrl]);
});
}
PS: 7 이상의 모든 버전에서 테스트 및 동작.
편집
새로운 버전의 Angular(5.1+)의 경우 @Simon McClive에서 제안하는 답변을 사용합니다.
구답
Angular에 대한 GitHub 기능 요청에서 이 회피책을 찾았습니다.
this._router.routeReuseStrategy.shouldReuseRoute = function(){
return false;
};
this._router.events.subscribe((evt) => {
if (evt instanceof NavigationEnd) {
this._router.navigated = false;
window.scrollTo(0, 0);
}
});
이것을 app.component.ts에 추가하려고 했습니다. ngOnInit
작동했고, 확실히 작동했습니다. 같은 로드됩니다.component
을 사용하다
GitHub의 mihaicux2에 크레딧이 돌아간다.
는 이것을 버전 는 version version version 에서 테스트했습니다.4.0.0-rc.3
import { Router, NavigationEnd } from '@angular/router';
navigate()를 사용해도 브라우저의 주소 표시줄에 이미 표시된 URL이 변경되지 않으면 라우터는 아무것도 할 수 없습니다.데이터를 갱신하는 것은 라우터의 일이 아닙니다.데이터를 새로 고치려면 컴포넌트에 주입된 서비스를 생성하고 해당 서비스에서 로드 함수를 호출합니다.새 데이터가 검색될 경우 바인딩으로 보기를 업데이트합니다.
이게 앵글12에서 했던 거예요9 이하 버전에서는 동작하는지는 잘 모르겠습니다.
새로고침이 필요한 경우 이 명령을 호출해야 합니다.
this.router.navigate([], {
skipLocationChange: true,
queryParamsHandling: 'merge' //== if you need to keep queryParams
})
라우터 forRoot에서 SameUrlNavigation을 'reload'로 설정해야 합니다.
RouterModule.forRoot(appRoutes, {
// ..
onSameUrlNavigation: 'reload',
// ..
})
또한 모든 경로에서 runGuardsAndResolvers를 '항상'으로 설정해야 합니다.
{
path: '',
data: {},
runGuardsAndResolvers: 'always'
},
이건 내게 마법처럼 통한다
this.router.navigateByUrl('/', {skipLocationChange: true}).then(()=>
this.router.navigate([<route>]));
조금 까다롭습니다.같은 경로를 사용하여 더미 파라미터를 설정합니다.예를 들면...
refresh(){
this.router.navigate(["/same/route/path?refresh=1"]);
}
각도 2-4 루트 새로고침 해킹
루트 컴포넌트(모든 루트에 존재하는 컴포넌트) 내에서 다음 방법을 사용하면 됩니다.
onRefresh() {
this.router.routeReuseStrategy.shouldReuseRoute = function(){return false;};
let currentUrl = this.router.url + '?';
this.router.navigateByUrl(currentUrl)
.then(() => {
this.router.navigated = false;
this.router.navigate([this.router.url]);
});
}
파라미터 변경 시 새로고침 페이지는 발생하지 않습니다.이거 정말 좋은 기능이에요.페이지를 새로고침할 필요는 없지만 컴포넌트 값을 변경해야 합니다.paramChange 메서드는 URL 변경을 호출합니다.컴포넌트 데이터를 갱신할 수 있습니다.
/product/: id / details
import { ActivatedRoute, Params, Router } from ‘@angular/router’;
export class ProductDetailsComponent implements OnInit {
constructor(private route: ActivatedRoute, private router: Router) {
this.route.params.subscribe(params => {
this.paramsChange(params.id);
});
}
// Call this method on page change
ngOnInit() {
}
// Call this method on change of the param
paramsChange(id) {
}
앵귤러 내부 작업을 손댈 필요가 없는 빠르고 간단한 솔루션을 찾았습니다.
기본적으로: 같은 행선지 모듈을 사용하여 대체 루트를 작성하고 이들 모듈을 전환하기만 하면 됩니다.
const routes: Routes = [
{
path: 'gesuch',
loadChildren: './sections/gesuch/gesuch.module#GesuchModule'
},
{
path: 'gesuch-neu',
loadChildren: './sections/gesuch/gesuch.module#GesuchModule'
}
];
전환 메뉴는 다음과 같습니다.
<ul class="navigation">
<li routerLink="/gesuch-neu" *ngIf="'gesuch' === getSection()">Gesuch</li>
<li routerLink="/gesuch" *ngIf="'gesuch' !== getSection()">Gesuch</li>
</ul>
도움이 되었으면 좋겠다:)
저는 하드코딩을 하고 있습니다
this.router.routeReuseStrategy.shouldReuseRoute = function() {
return false;
// or
return true;
};
솔루션:
URL 매개 변수를 구독하고 구성 요소를 초기화합니다.트릭은 필요 없습니다.처음 로드를 포함한 "new URL --> new data" 뿐입니다.
URL 파라미터의 경우(예:/persons/:id
constructor(protected activeRoute: ActivatedRoute, ...) {
this.activeRoute.paramMap.subscribe(paramMap => {
const id = paramMap.get('id'); // get param from dictonary
this.load(id); // load your data
});
}
URL 쿼리 파라미터의 경우(예:?q=...&returnUrl=...
)(통상은 필수가 아닙니다):
this.activeRoute.queryParamMap.subscribe(queryParamMap => {
const returnUrl = queryParamMap.get('returnUrl');
...
});
문제의 원인은 다음과 같습니다.
URL이 변경되면 Angular는 가능하면 이전 구성 요소를 재사용하여 컴퓨터 리소스를 절약합니다.데이터 로딩은 사용자 지정 코드이므로 Angular가 대신 할 수 없습니다.
입 가져오기Router
★★★★★★★★★★★★★★★★★」ActivatedRoute
부에서@angular/router
import { ActivatedRoute, Router } from '@angular/router';
주 주입Router
★★★★★★★★★★★★★★★★★」ActivatedRoute
( case)( you)(요)에서 필요한 경우)
constructor(
private router: Router,
private route: ActivatedRoute,
) {}
필요한 경우 URL에서 원하는 파라미터를 가져옵니다.
const appointmentId = this.route.snapshot.paramMap.get('appointmentIdentifier');
더미 또는 메인 URL로 이동한 후 실제 URL로 이동하여 트릭을 사용하면 구성 요소가 새로 고쳐집니다.
this.router.navigateByUrl('/appointments', { skipLocationChange: true }).then(() => {
this.router.navigate([`appointment/${appointmentId}`])
});
고객님의 경우
const id= this.route.snapshot.paramMap.get('id');
this.router.navigateByUrl('/departments', { skipLocationChange: true }).then(() => {
this.router.navigate([`departments/${id}/employees`]);
});
더미 루트를 사용하는 경우 찾을 수 없는 URL을 구현한 경우 URL과 일치하지 않을 경우 제목 깜박임이 "Not Found"로 표시됩니다.
해결책은 다음과 같이 링크가 항상 새로고침되는 더미 파라미터(초단위 시간)를 전달하는 것입니다.
this.router.navigate(["/url", {myRealData: RealData, dummyData: (new Date).getTime()}])
조금 하드코어지만
this.router.onSameUrlNavigation = 'reload';
this.router.navigateByUrl(this.router.url).then(() => {
this.router.onSameUrlNavigation = 'ignore';
});
route.navigate() 메서드에서 OnInit을 구현하고 ngOnInit()을 호출합니다.
예를 참조해 주세요.
export class Component implements OnInit {
constructor() { }
refresh() {
this.router.navigate(['same-route-here']);
this.ngOnInit(); }
ngOnInit () {
}
미 포 컴 넌 트 트 용 사 나 결 해 했 습다 solved니 a시유를 and for오 component사 scenario한리여루하 by를 route더reload
, 사실이에요.redirect
모든 사용자의 시나리오를 커버하는 것은 아니지만, 제 시나리오에서는 유효했습니다.
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { Http } from '@angular/http';
@Component({
selector: 'reload',
template: `
<h1>Reloading...</h1>
`,
})
export class ReloadComponent implements OnInit{
constructor(private router: Router, private route: ActivatedRoute) {
}
ngOnInit() {
const url = this.route.snapshot.pathFromRoot.pop().url.map(u => u.path).join('/');
this.router.navigateByUrl(url);
}
}
와일드카드를 사용하여 모든 URL을 캐치하도록 라우팅이 배선되어 있습니다.
import { RouterModule } from '@angular/router';
import { NgModule } from '@angular/core';
import { LoginViewComponent } from './views/login/login.component';
import { HomeViewComponent } from './views/home/home.component';
import { ReloadComponent } from './views/reload/reload.component';
@NgModule({
declarations: [
LoginViewComponent, HomeViewComponent, ReloadComponent
],
imports: [
RouterModule.forRoot([
{ path: 'login', component: LoginViewComponent },
{ path: 'home', component: HomeViewComponent },
{
path: 'reload',
children: [{
path: '**',
component: ReloadComponent
}]
},
{ path: '**', redirectTo: 'login'}
])
],
exports: [
RouterModule,
],
providers: [],
})
export class AppRoutingModule {}
이것을 사용하려면 , 다음의 URL 에 새로고침을 추가할 필요가 있습니다.
this.router.navigateByUrl('reload/some/route/again/fresh', {skipLocationChange: true})
현재 경로를 새로 고치는 방법은 여러 가지가 있습니다.
라우터 동작을 변경합니다(Angular 5.1 이후).SameUrlNavigation의 라우터를 'reload'로 설정합니다.이것에 의해, 같은 URL 네비게이션으로 라우터 이벤트가 송신됩니다.
- 그런 다음 루트에 가입하여 처리할 수 있습니다.
- runGuardsAndResolvers 조합과 함께 사용하여 해결 프로그램을 다시 실행할 수 있습니다.
라우터를 손대지 않은 채로 두다
- URL의 현재 타임스탬프와 함께 refresh queryParam을 전달하고 라우팅된 컴포넌트의 queryParam에 서브스크라이브합니다.
- router-outlet의 activate Event를 사용하여 루티드컴포넌트를 입수합니다.
자세한 설명은 https://medium.com/@kevinkreuzer/current-route-in-current-route-in-current-in-current-current-in-current-current-in-curret
이게 도움이 됐으면 좋겠다.
사용하고 있다setTimeout
그리고.navigationByUrl
이 문제를 해결하기 위해...그리고 그것은 나에게 잘 작동하고 있다.
다른 URL로 리디렉션되고 대신 현재 URL로 다시 전송됩니다.
setTimeout(() => {
this.router.navigateByUrl('/dashboard', {skipLocationChange: false}).then(() =>
this.router.navigate([route]));
}, 500)
Angular가 아직도 이에 대한 좋은 해결책을 제시하지 못한 것 같아 매우 실망스럽습니다.여기서 기트허브 문제를 제기했습니다.https://github.com/angular/angular/issues/31843
그 사이에, 이것은 나의 회피책이다.위에서 제시한 다른 솔루션 중 몇 가지를 기반으로 구축되어 있지만, 조금 더 견고하다고 생각합니다.라우터 서비스를 "로 감싸야 합니다.ReloadRouter
"는 새로고침 기능을 처리하고, 또한RELOAD_PLACEHOLDER
코어 라우터의 설정으로 이행합니다.이것은 중간 네비게이션에 사용되며 다른 루트(또는 가드)의 트리거를 방지합니다.
주의: 다음 항목만 사용하십시오.ReloadRouter
새로고침 기능을 필요로 하는 경우.표준 사용Router
그렇지않으면.
import { Injectable } from '@angular/core';
import { NavigationExtras, Router } from '@angular/router';
@Injectable({
providedIn: 'root'
})
export class ReloadRouter {
constructor(public readonly router: Router) {
router.config.unshift({ path: 'RELOAD_PLACEHOLDER' });
}
public navigate(commands: any[], extras?: NavigationExtras): Promise<boolean> {
return this.router
.navigateByUrl('/RELOAD_PLACEHOLDER', {skipLocationChange: true})
.then(() => this.router.navigate(commands, extras));
}
}
함수를 작성합니다(예:reloadCurrentPage
.~하듯이window
Angular 컴포넌트에서 직접 재사용할 수 있는 글로벌 객체입니다.window.location.reload()
는 현재 액티브한 페이지를 새로고침 합니다.
function reloadCurrentPage() {
window.location.reload();
}
내 경우:
const navigationExtras: NavigationExtras = {
queryParams: { 'param': val }
};
this.router.navigate([], navigationExtras);
올바르게 동작하다
새로고침할 컴포넌트의 경로가view
다음 명령을 사용합니다.
this.router.routeReuseStrategy.shouldReuseRoute = function (future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot) {
if (future.url.toString() === 'view' && curr.url.toString() === future.url.toString()) {
return false;
}
return (future.routeConfig === curr.routeConfig);
};
를 추가할 수 있습니다.debugger
메서드 내에서는 에 네비게이트 한 후 정확한 루트가 무엇인지 알 수 있습니다."departments/:id/employees"
.
값싸고 놀라운 방법이네요.
this.router.navigate([], {
relativeTo: this.route,
queryParams: {
...this.route.snapshot.queryParams,
// replace 't' with any others not to conflict with exsiting
// '2^11' prevents reloading in about 2 seconds
t: Date.now() >> 11,
skipLocationChange: true,
},
});
서브스크라이브, 루트 파라미터 변경
// parent param listener ie: "/:id"
this.route.params.subscribe(params => {
// do something on parent param change
let parent_id = params['id']; // set slug
});
// child param listener ie: "/:id/:id"
this.route.firstChild.params.subscribe(params => {
// do something on child param change
let child_id = params['id'];
});
라우터 링크 경유로 루트를 변경하는 경우는, 다음의 순서에 따릅니다.
constructor(public routerNavigate: Router){
this.router.routeReuseStrategy.shouldReuseRoute = function () {
return false;
};
this.router.events.subscribe((evt) => {
if (evt instanceof NavigationEnd) {
this.router.navigated = false;
}
})
}
다음 코드가 작동합니다.
logoFn(url: any) {
this.router.routeReuseStrategy.shouldReuseRoute = function () {
return false;
};
this.router.navigate(['']); or
this.router.navigate([url]);
}
이 문제는 Angular 6+에서 (네이티브하게) 해결되었다고 생각합니다.확인해 주세요.
https://medium.com/engineering-on-the-incline/reloading-current-route-on-click-angular-5-1a1bfc740ab2 를 참조해 주세요.
그러나 이는 전체 경로(모든 어린이 경로 포함)에 대해 작동합니다.
단일 컴포넌트를 대상으로 하는 경우 다음과 같이 변경합니다.변경되는 쿼리 파라미터를 사용하여 원하는 횟수만큼 탐색할 수 있습니다.
내비게이션 포인트(클래스)
this.router.navigate(['/route'], {
queryParams: { 'refresh': Date.now() }
});
"새로고침/새로고침"할 구성 요소
// . . . Component Class Body
$_route$: Subscription;
constructor (private _route: ActivatedRoute) {}
ngOnInit() {
this.$_route$ = this._route.queryParams.subscribe(params => {
if (params['refresh']) {
// Do Something
// Could be calling this.ngOnInit() PS: I Strongly advise against this
}
});
}
ngOnDestroy() {
// Always unsubscribe to prevent memory leak and unexpected behavior
this.$_route$.unsubscribe();
}
// . . . End of Component Class Body
루트를 저장할 타이밍을 결정합니다.false를 반환한다.
this.router.routeReuseStrategy.shouldReuseRoute = function () {
return false;
};
라우터의 네비게이션 값을 false로 설정하면 이 루트가 라우팅되지 않았음을 알 수 있습니다.
this.mySubscription = this.router.events.subscribe(event => {
if (event instanceof NavigationEnd) {
this.router.navigated = false;
}
});
언급URL : https://stackoverflow.com/questions/40983055/how-to-reload-the-current-route-with-the-angular-2-router
'sourcecode' 카테고리의 다른 글
AngularJS + Django Rest Framework + CORS (CSRF Cookie가 클라이언트에 표시되지 않음) (0) | 2023.04.03 |
---|---|
TypeScript, React, Eslint 및 단순 Arrow 함수 컴포넌트 문제 (0) | 2023.04.03 |
JQuery $.ajax() post - Java 서블릿의 데이터 (0) | 2023.04.03 |
각도용 리치 텍스트 편집기JS (0) | 2023.04.03 |
FeedWordpress Import에 속하는 이미지의 사이즈가 조정됩니다만, 어디에 있습니까? (0) | 2023.04.03 |