development

Angular 2 라우터로 현재 경로를 다시로드하는 방법

big-blog 2020. 8. 27. 08:15
반응형

Angular 2 라우터로 현재 경로를 다시로드하는 방법


해시 위치 전략과 함께 각도 2를 사용하고 있습니다.

구성 요소는 해당 경로로로드됩니다.

"departments/:id/employees"

지금까지는 괜찮습니다.

여러 편집 된 테이블 행을 성공적으로 일괄 저장 한 후 다음을 통해 현재 경로 URL을 다시로드하고 싶습니다.

this.router.navigate([`departments/${this.id}/employees`]);

하지만 아무 일도 일어나지 않습니다. 왜?


navigate ()가 브라우저의 주소 표시 줄에 이미 표시된 URL을 변경하지 않으면 라우터가 할 일이 없습니다. 데이터를 새로 고치는 것은 라우터의 일이 아닙니다. 데이터를 새로 고치려면 구성 요소에 삽입 된 서비스를 만들고 서비스에서로드 기능을 호출합니다. 새 데이터가 검색되면 바인딩을 통해 뷰를 업데이트합니다.


이제 onSameUrlNavigation라우터 구성 속성을 사용하여 Angular 5.1에서이 작업을 수행 할 수 있습니다 .

여기에 방법을 설명하는 블로그를 추가했지만 그 요지는 다음과 같습니다.

https://medium.com/engineering-on-the-incline/reloading-current-route-on-click-angular-5-1a1bfc740ab2

라우터 구성 활성화 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',
 }
]

마지막으로 다시로드를 활성화하려는 각 구성 요소에서 이벤트를 처리해야합니다. 이는 라우터를 가져오고 이벤트에 바인딩하고 구성 요소의 상태를 재설정하고 필요한 경우 데이터를 다시 가져 오는 초기화 메서드를 호출하여 수행 할 수 있습니다.

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에 대한 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 기능 요청에 연결

크레딧은 GitHub의 mihaicux2 로 이동합니다 .

나는 이것을 버전 4.0.0-rc.3에서 테스트 했다.import { Router, NavigationEnd } from '@angular/router';


컨트롤러에서 예상되는 경로로 리디렉션하는 함수를 만듭니다.

redirectTo(uri:string){
this.router.navigateByUrl('/DummyComponent', {skipLocationChange: true}).then(()=>
this.router.navigate([uri]));}

다음과 같이 사용하십시오

this.redirectTo('//place your uri here');

이 기능은 더미 경로로 리디렉션하고 사용자가 알지 못하는 사이에 대상 경로로 빠르게 돌아갑니다.


약간 까다 로움 : 일부 더미 매개 변수와 동일한 경로를 사용합니다. 예를 들면

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]);
    });
  }

이건 나에게 매력처럼 일해

this.router.navigateByUrl('/', {skipLocationChange: true}).then(()=>
this.router.navigate([<route>]));

매개 변수 변경시 다시로드 페이지가 발생하지 않습니다. 이것은 정말 좋은 기능입니다. 페이지를 다시로드 할 필요는 없지만 구성 요소의 값을 변경해야합니다. 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'
  }
];

그리고 여기 toggeling 메뉴 :

<ul class="navigation">
    <li routerLink="/gesuch-neu" *ngIf="'gesuch' === getSection()">Gesuch</li>
    <li routerLink="/gesuch" *ngIf="'gesuch' !== getSection()">Gesuch</li>
</ul>

도움이되기를 바랍니다 :)


나의 경우에는:

const navigationExtras: NavigationExtras = {
    queryParams: { 'param': val }
};

this.router.navigate([], navigationExtras);

올바른 일


나를 위해 하드 코딩 작업

this.router.routeReuseStrategy.shouldReuseRoute = function() {
    return false;
    // or
    return true;
};

OnInit를 구현하고 route.navigate () 메서드에서 ngOnInit ()를 호출합니다.

예를 참조하십시오.

export class Component implements OnInit {

  constructor() {   }

  refresh() {
    this.router.navigate(['same-route-here']);
    this.ngOnInit();   }

  ngOnInit () {

  }

대한 더미의 구성 요소 및 경로를 사용하여 유사한 시나리오를 해결 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에 reload를 추가하기 만하면됩니다 :

  this.router.navigateByUrl('reload/some/route/again/fresh', {skipLocationChange: true})

약간 하드 코어하지만

this.router.onSameUrlNavigation = 'reload';
this.router.navigateByUrl(this.router.url).then(() => {

    this.router.onSameUrlNavigation = 'ignore';

});

현재 경로를 새로 고치는 방법에는 여러 가지가 있습니다.

라우터 동작 변경 (Angular 5.1 이후) 라우터 onSameUrlNavigation을 '다시로드'로 설정합니다. 그러면 동일한 URL 탐색에서 라우터 이벤트가 발생합니다.

  • 그런 다음 경로를 구독하여 처리 할 수 ​​있습니다.
  • runGuardsAndResolvers의 조합과 함께 사용하여 리졸버를 다시 실행할 수 있습니다.

라우터는 그대로 둡니다.

  • URL에 현재 타임 스탬프가있는 새로 고침 queryParam을 전달하고 라우팅 된 구성 요소에서 queryParams를 구독합니다.
  • 라우터 콘센트의 활성화 이벤트를 사용하여 라우팅 된 구성 요소를 확보합니다.

https://medium.com/@kevinkreuzer/refresh-current-route-in-angular-512a19d58f6e 아래에 더 자세한 설명을 작성했습니다.

도움이 되었기를 바랍니다.


내가 아는 한 Angular 2의 라우터로는이 작업을 수행 할 수 없지만 다음과 같이 할 수 있습니다.

window.location.href = window.location.href

보기를 다시로드합니다.


새로 고치려는 구성 요소의 경로가라고 가정하고 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(["/url", {myRealData: RealData, dummyData: (new Date).getTime()}])

이 문제를 해결하기 위해 사용 setTimeout하고 있으며 navigationByUrl... 잘 작동합니다.

다른 URL로 리디렉션되고 대신 현재 URL에 다시 표시됩니다.

 setTimeout(() => {
     this.router.navigateByUrl('/dashboard', {skipLocationChange: false}).then(() =>
           this.router.navigate([route]));
     }, 500)

나는 이것이 Angular 6+에서 (기본적으로) 해결되었다고 믿습니다. 검사

그러나 이것은 전체 경로에서 작동합니다 (모든 하위 경로도 포함)

단일 구성 요소를 대상으로하는 경우 방법은 다음과 같습니다. 변경되는 쿼리 매개 변수를 사용하여 원하는만큼 탐색 할 수 있습니다.

탐색 지점 (클래스)

   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

Angular 7 프로젝트에 이것을 사용하고 있습니다.

reloadCurrentRoute() {
    let currentUrl = this.router.url;
    this.router.navigateByUrl('/', {skipLocationChange: true}).then(() => {
        this.router.navigate([currentUrl]);
    });
}

경로 매개 변수 변경에 가입

    // 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;
             }
          })
      }

Very frustrating that Angular still doesn't seem to include a good solution for this. I have raised a github issue here: https://github.com/angular/angular/issues/31843

In the meantime, this is my workaround. It builds on some of the other solutions suggested above, but I think it's a little more robust. It involves wrapping the Router service in a "ReloadRouter", which takes care of the reload functionality and also adds a RELOAD_PLACEHOLDER to the core router configuration. This is used for the interim navigation and avoids triggering any other routes (or guards).

Note: Only use the ReloadRouter in those cases when you want the reload functionality. Use the normal Router otherwise.

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));
  }
}

You should use "onSameUrlNavigation" property in RouterModule and then subscribe to Route events https://blog.angularindepth.com/refresh-current-route-in-angular-512a19d58f6e


enter image description here

The same route reload Angular 6


This below code will work:

logoFn(url: any) {

    this.router.routeReuseStrategy.shouldReuseRoute = function () {
        return false;
    };
    this.router.navigate(['']); or
    this.router.navigate([url]);

}

This worked for me:

let url = `departments/${this.id}/employees`;

this.router.navigated = false;
this.router.navigateByUrl(url);

reload current route in angular 2 very helpful link to reload current route in angualr 2 or 4

in this define two technique to do this

  1. with dummy query params
  2. with dummy route

for more see above link


Try this

window.open('dashboard', '_self');

its old method but works on all angular version, where it redirect on route and refresh the page.

참고URL : https://stackoverflow.com/questions/40983055/how-to-reload-the-current-route-with-the-angular-2-router

반응형