アンダースさん、いい質問ですね!
私はあなたとほぼ同じユースケースを持っていて、同じことをしたいと思っていました! ユーザー検索>結果を取得>ユーザーが結果に移動>ユーザーが戻ってナビゲート> BOOM blazing fast return to resultsですが、ユーザーが移動した特定の結果を保存したくありません。
tl;dr
RouteReuseStrategy
で戦略を実装して提供するクラスが必要ですngModule
。ルートを保存するタイミングを変更したい場合は、shouldDetach
関数を変更します。が返されるtrue
と、Angular はルートを保存します。ルートのアタッチ時に変更する場合は、shouldAttach
関数を変更します。trueをshouldAttach
返すと、Angular は要求されたルートの代わりに保存されたルートを使用します。これが、遊んでみるプランカーです。
RouteReuseStrategy について
この質問をすることで、RouteReuseStrategy を使用すると、Angular にコンポーネントを破棄するのではなく、後で再レンダリングするために保存するように指示できることをすでに理解しています。それができるので、それはクールです:
- サーバー呼び出しの減少
- スピードアップ
- ANDコンポーネントは、デフォルトで、そのままの状態でレンダリングされます
たとえば、ユーザーが大量のテキストをページに入力したにもかかわらず、一時的にページを離れたい場合、最後の 1 つは重要です。フォームが多すぎるため、エンタープライズ アプリケーションはこの機能を気に入るはずです。
これは私が問題を解決するために思いついたものです。あなたが言ったようにRouteReuseStrategy
、バージョン 3.4.1 以降で @angular/router によって提供される を利用する必要があります。
TODO
まず、プロジェクトに @angular/router バージョン 3.4.1 以降があることを確認してください。
次に、実装するクラスを格納するファイルを作成しますRouteReuseStrategy
。私は私に電話し、保管のためにフォルダーにreuse-strategy.ts
入れました。/app
今のところ、このクラスは次のようになります。
import { RouteReuseStrategy } from '@angular/router';
export class CustomReuseStrategy implements RouteReuseStrategy {
}
(TypeScript エラーについて心配する必要はありません。すべてを解決しようとしています)
にクラスを提供して、基礎を完成app.module
させます。あなたはまだ書いていないことに注意しCustomReuseStrategy
てimport
くださいreuse-strategy.ts
. またimport { RouteReuseStrategy } from '@angular/router';
@NgModule({
[...],
providers: [
{provide: RouteReuseStrategy, useClass: CustomReuseStrategy}
]
)}
export class AppModule {
}
最後の部分は、ルートが切り離され、保存され、取得され、再接続されるかどうかを制御するクラスを作成することです。古いコピー/貼り付けに入る前に、ここで仕組みについて簡単に説明します。私が説明しているメソッドについては、以下のコードを参照してください。もちろん、コードにはたくさんのドキュメントがあります。
- ナビゲートすると
shouldReuseRoute
発火します。これは私には少し奇妙ですが、 が返された場合、true
現在のルートが実際に再利用され、他のメソッドは起動されません。ユーザーが別の場所に移動している場合は、false を返します。
shouldReuseRoute
を返す場合false
、shouldDetach
起動します。shouldDetach
ルートを保存するかどうかを決定し、それをboolean
示す を返します。ここで、 paths を保存するか保存しないかを決定する必要があります。これは、保存するパスの配列をチェックし、配列に存在しない場合は false を返すことで行います。route.routeConfig.path
path
shouldDetach
が返さtrue
れた場合はstore
、ルートについて必要な情報を保存する機会が与えられます。何をするにしても、保存する必要があります。これは、DetachedRouteHandle
Angular が後で保存されたコンポーネントを識別するために使用するものだからです。DetachedRouteHandle
以下では、と の両方ActivatedRouteSnapshot
をクラスのローカル変数に格納します。
さて、ストレージのロジックを見てきましたが、コンポーネントへの移動はどうでしょうか? Angular はどのようにしてナビゲーションを傍受し、保存されたものをその場所に配置することを決定するのでしょうか?
- ここでも、
shouldReuseRoute
が を返した後false
、shouldAttach
が実行されます。これは、コンポーネントを再生成するか、メモリ内で使用するかを判断するチャンスです。保存されたコンポーネントを再利用したい場合は、戻っtrue
てきてください。
- ここで、Angular は「どのコンポーネントを使用しますか?」と尋ねますが、そのコンポーネントの
DetachedRouteHandle
fromを返すことで、それを示しますretrieve
。
必要なロジックはこれでほぼすべてです。以下の のコードにはreuse-strategy.ts
、2 つのオブジェクトを比較する気の利いた関数も残しています。route.params
これを使用して、将来のルートとroute.queryParams
保存されているルートを比較します。それらがすべて一致する場合、新しいコンポーネントを生成する代わりに、保存されたコンポーネントを使用したいと考えています。でも、やり方はあなた次第!
再利用-strategy.ts
/**
* reuse-strategy.ts
* by corbfon 1/6/17
*/
import { ActivatedRouteSnapshot, RouteReuseStrategy, DetachedRouteHandle } from '@angular/router';
/** Interface for object which can store both:
* An ActivatedRouteSnapshot, which is useful for determining whether or not you should attach a route (see this.shouldAttach)
* A DetachedRouteHandle, which is offered up by this.retrieve, in the case that you do want to attach the stored route
*/
interface RouteStorageObject {
snapshot: ActivatedRouteSnapshot;
handle: DetachedRouteHandle;
}
export class CustomReuseStrategy implements RouteReuseStrategy {
/**
* Object which will store RouteStorageObjects indexed by keys
* The keys will all be a path (as in route.routeConfig.path)
* This allows us to see if we've got a route stored for the requested path
*/
storedRoutes: { [key: string]: RouteStorageObject } = {};
/**
* Decides when the route should be stored
* If the route should be stored, I believe the boolean is indicating to a controller whether or not to fire this.store
* _When_ it is called though does not particularly matter, just know that this determines whether or not we store the route
* An idea of what to do here: check the route.routeConfig.path to see if it is a path you would like to store
* @param route This is, at least as I understand it, the route that the user is currently on, and we would like to know if we want to store it
* @returns boolean indicating that we want to (true) or do not want to (false) store that route
*/
shouldDetach(route: ActivatedRouteSnapshot): boolean {
let detach: boolean = true;
console.log("detaching", route, "return: ", detach);
return detach;
}
/**
* Constructs object of type `RouteStorageObject` to store, and then stores it for later attachment
* @param route This is stored for later comparison to requested routes, see `this.shouldAttach`
* @param handle Later to be retrieved by this.retrieve, and offered up to whatever controller is using this class
*/
store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void {
let storedRoute: RouteStorageObject = {
snapshot: route,
handle: handle
};
console.log( "store:", storedRoute, "into: ", this.storedRoutes );
// routes are stored by path - the key is the path name, and the handle is stored under it so that you can only ever have one object stored for a single path
this.storedRoutes[route.routeConfig.path] = storedRoute;
}
/**
* Determines whether or not there is a stored route and, if there is, whether or not it should be rendered in place of requested route
* @param route The route the user requested
* @returns boolean indicating whether or not to render the stored route
*/
shouldAttach(route: ActivatedRouteSnapshot): boolean {
// this will be true if the route has been stored before
let canAttach: boolean = !!route.routeConfig && !!this.storedRoutes[route.routeConfig.path];
// this decides whether the route already stored should be rendered in place of the requested route, and is the return value
// at this point we already know that the paths match because the storedResults key is the route.routeConfig.path
// so, if the route.params and route.queryParams also match, then we should reuse the component
if (canAttach) {
let willAttach: boolean = true;
console.log("param comparison:");
console.log(this.compareObjects(route.params, this.storedRoutes[route.routeConfig.path].snapshot.params));
console.log("query param comparison");
console.log(this.compareObjects(route.queryParams, this.storedRoutes[route.routeConfig.path].snapshot.queryParams));
let paramsMatch: boolean = this.compareObjects(route.params, this.storedRoutes[route.routeConfig.path].snapshot.params);
let queryParamsMatch: boolean = this.compareObjects(route.queryParams, this.storedRoutes[route.routeConfig.path].snapshot.queryParams);
console.log("deciding to attach...", route, "does it match?", this.storedRoutes[route.routeConfig.path].snapshot, "return: ", paramsMatch && queryParamsMatch);
return paramsMatch && queryParamsMatch;
} else {
return false;
}
}
/**
* Finds the locally stored instance of the requested route, if it exists, and returns it
* @param route New route the user has requested
* @returns DetachedRouteHandle object which can be used to render the component
*/
retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle {
// return null if the path does not have a routerConfig OR if there is no stored route for that routerConfig
if (!route.routeConfig || !this.storedRoutes[route.routeConfig.path]) return null;
console.log("retrieving", "return: ", this.storedRoutes[route.routeConfig.path]);
/** returns handle when the route.routeConfig.path is already stored */
return this.storedRoutes[route.routeConfig.path].handle;
}
/**
* Determines whether or not the current route should be reused
* @param future The route the user is going to, as triggered by the router
* @param curr The route the user is currently on
* @returns boolean basically indicating true if the user intends to leave the current route
*/
shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
console.log("deciding to reuse", "future", future.routeConfig, "current", curr.routeConfig, "return: ", future.routeConfig === curr.routeConfig);
return future.routeConfig === curr.routeConfig;
}
/**
* This nasty bugger finds out whether the objects are _traditionally_ equal to each other, like you might assume someone else would have put this function in vanilla JS already
* One thing to note is that it uses coercive comparison (==) on properties which both objects have, not strict comparison (===)
* Another important note is that the method only tells you if `compare` has all equal parameters to `base`, not the other way around
* @param base The base object which you would like to compare another object to
* @param compare The object to compare to base
* @returns boolean indicating whether or not the objects have all the same properties and those properties are ==
*/
private compareObjects(base: any, compare: any): boolean {
// loop through all properties in base object
for (let baseProperty in base) {
// determine if comparrison object has that property, if not: return false
if (compare.hasOwnProperty(baseProperty)) {
switch(typeof base[baseProperty]) {
// if one is object and other is not: return false
// if they are both objects, recursively call this comparison function
case 'object':
if ( typeof compare[baseProperty] !== 'object' || !this.compareObjects(base[baseProperty], compare[baseProperty]) ) { return false; } break;
// if one is function and other is not: return false
// if both are functions, compare function.toString() results
case 'function':
if ( typeof compare[baseProperty] !== 'function' || base[baseProperty].toString() !== compare[baseProperty].toString() ) { return false; } break;
// otherwise, see if they are equal using coercive comparison
default:
if ( base[baseProperty] != compare[baseProperty] ) { return false; }
}
} else {
return false;
}
}
// returns true only after false HAS NOT BEEN returned through all loops
return true;
}
}
行動
この実装では、ユーザーがルーター上で 1 回だけ訪れたすべての一意のルートが保存されます。これは、サイトでのユーザーのセッション中、メモリに保存されているコンポーネントに追加され続けます。保存するルートを制限したい場合、それを行う場所はshouldDetach
メソッドです。保存するルートを制御します。
例
ユーザーがホームページから何かを検索し、パスに移動するとします。パスは のsearch/:term
ように表示される場合がありますwww.yourwebsite.com/search/thingsearchedfor
。検索ページには、多数の検索結果が含まれています。彼らが戻ってきた場合に備えて、このルートを保存したいと思います! ここで、ユーザーは検索結果をクリックして に移動しview/:resultId
ますが、これはおそらく 1 回しか表示されないため、保存したくありません。上記の実装が整ったら、shouldDetach
メソッドを変更するだけです! これは次のようになります。
まず、保存したいパスの配列を作成しましょう。
private acceptedRoutes: string[] = ["search/:term"];
これで、配列に対してshouldDetach
をチェックできます。route.routeConfig.path
shouldDetach(route: ActivatedRouteSnapshot): boolean {
// check to see if the route's path is in our acceptedRoutes array
if (this.acceptedRoutes.indexOf(route.routeConfig.path) > -1) {
console.log("detaching", route);
return true;
} else {
return false; // will be "view/:resultId" when user navigates to result
}
}
Angular はルートのインスタンスを 1 つだけ保存search/:term
するため、このストレージは軽量になり、他のすべてではなく、 にあるコンポーネントのみを保存します!
追加リンク
まだ多くのドキュメントはありませんが、存在するものへのリンクをいくつか示します。
Angular ドキュメント: https://angular.io/docs/ts/latest/api/router/index/RouteReuseStrategy-class.html
紹介記事: https://www.softwarearchitekt.at/post/2016/12/02/sticky-routes-in-angular-2-3-with-routereusestrategy.aspx
Nativescript-angular のRouteReuseStrategyのデフォルト実装: https://github.com/NativeScript/nativescript-angular/blob/cb4fd3a/nativescript-angular/router/ns-route-reuse-strategy.ts