私はhashlocation戦略でangular 2を使用しています。
コンポーネントはそのルートで読み込まれます:
"departments/:id/employees"
これまでのところ結構です。
編集した複数のテーブル行をバッチ保存した後、次の方法で現在のルートURLを再ロードします。
this.router.navigate([`departments/${this.id}/employees`]);
しかし、何も起こりません、なぜですか?
私はhashlocation戦略でangular 2を使用しています。
コンポーネントはそのルートで読み込まれます:
"departments/:id/employees"
これまでのところ結構です。
編集した複数のテーブル行をバッチ保存した後、次の方法で現在のルートURLを再ロードします。
this.router.navigate([`departments/${this.id}/employees`]);
しかし、何も起こりません、なぜですか?
回答:
navigate()がブラウザーのアドレスバーに既に表示されているURLを変更しない場合、ルーターは何もする必要がありません。データを更新するのはルーターの仕事ではありません。データを更新する場合は、コンポーネントに挿入されたサービスを作成し、サービスでロード機能を呼び出します。新しいデータが取得される場合、バインディングを介してビューが更新されます。
これは、Angular 5.1でonSameUrlNavigation
ルーター構成のプロパティを使用して行うことができます。
ここに方法を解説したブログを追加しましたが、要点は以下の通りです
router config enable 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();
}
}
}
これらのすべての手順を実行したら、ルートの再読み込みを有効にする必要があります。
init
関数を呼び出す代わりにコンポーネントをリロードする方法はありますか
init
か?
予想されるルートにリダイレクトする関数をコントローラーに作成します
redirectTo(uri:string){
this.router.navigateByUrl('/', {skipLocationChange: true}).then(()=>
this.router.navigate([uri]));
}
次に、このように使用します
this.redirectTo('//place your uri here');
この関数は、ダミーのルートにリダイレクトし、ユーザーが気付かないうちにすばやく目的のルートに戻ります。
'/'
代わりに使用すると魅力的に機能します'/DummyComponent'
編集
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
およびデータがます。
クレジットはmihaicux2に送られます GitHubのれます。
私はこれをバージョン4.0.0-rc.3
でテストしましたimport { Router, NavigationEnd } from '@angular/router';
少しトリッキー:いくつかのダミーパラメーターで同じパスを使用します。例えば-
refresh(){
this.router.navigate(["/same/route/path?refresh=1"]);
}
this.router.navigate(['/pocetna'], { queryParams: { 'refresh': 1 } });
とroute.queryParams.subscribe(val => myRefreshMethod())
どこroute: ActivatedRoute
リフレッシュコンポーネントに注入された...希望、それが助け
私はこれをAngular 9プロジェクトに使用しています:
reloadCurrentRoute() {
let currentUrl = this.router.url;
this.router.navigateByUrl('/', {skipLocationChange: true}).then(() => {
this.router.navigate([currentUrl]);
});
}
PS:テスト済みで、「Angular 7、8」でも動作します
Angular 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) {
}
これがAngular 9でやったことです。これが古いバージョンで機能するかどうかはわかりません。
リロードする必要がある場合は、これを呼び出す必要があります。
this.router.navigate([], {
skipLocationChange: true,
queryParamsHandling: 'merge' //== if you need to keep queryParams
})
ルーターforRootでは、SameUrlNavigationを 'reload'に設定する必要があります
RouterModule.forRoot(appRoutes, {
// ..
onSameUrlNavigation: 'reload',
// ..
})
そして、すべてのルートでrunGuardsAndResolversを「always」に設定する必要があります
{
path: '',
data: {},
runGuardsAndResolvers: 'always'
},
私にとってハードコーディングは
this.router.routeReuseStrategy.shouldReuseRoute = function() {
return false;
// or
return true;
};
私の知る限り、Angular 2のルーターではこれを行うことはできません。
window.location.href = window.location.href
ビューを再読み込みします。
アンギュラーの内部の仕組みをいじくる必要のない、すばやく簡単なソリューションを見つけました。
基本的に:同じ宛先モジュールで代替ルートを作成し、それらを切り替えるだけです。
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.onSameUrlNavigation = 'reload';
this.router.navigateByUrl(this.router.url).then(() => {
this.router.onSameUrlNavigation = 'ignore';
});
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})
現在のルートを更新する方法はいくつかあります
ルーターの動作を変更する(Angular 5.1以降) ルーターのonSameUrlNavigationを「再読み込み」に設定します。これにより、同じURLナビゲーションでルーターイベントが発行されます。
ルーターはそのままにしておきます
https://medium.com/@kevinkreuzer/refresh-current-route-in-angular-512a19d58f6eに詳細な説明を書きました
お役に立てれば。
更新するコンポーネントのルートがであるとすると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"
。
これは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にはまだこれに対する良い解決策が含まれていないようで非常にイライラします。ここでgithubの問題を提起しました: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));
}
}
インポートRouter
とActivatedRoute
から@angular/router
import { ActivatedRoute, Router } from '@angular/router';
挿入Router
してActivatedRoute
(URLから何かが必要な場合)
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にも一致しない場合、タイトルが「見つかりません」と点滅します。
ルートパラメータの変更をサブスクライブする
// 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'];
});
RouterModuleの "onSameUrlNavigation"プロパティを使用して、Routeイベントにサブスクライブする必要があります https://blog.angularindepth.com/refresh-current-route-in-angular-512a19d58f6e
ルートを保存するタイミングを決定し、falseを返します
this.router.routeReuseStrategy.shouldReuseRoute = function () {
return false;
};
そして、ルーターのナビゲートされた値をfalseに設定します。これは、このルートがルーティングされなかったことを示します
this.mySubscription = this.router.events.subscribe(event => {
if (event instanceof NavigationEnd) {
this.router.navigated = false;
}
});