Гей Андерс, чудове запитання!
У мене майже такий самий випадок використання, що і у вас, і я хотів зробити те саме! Пошук користувачів> отримання результатів> Користувач переходить до результату> Користувач повертається назад> БУМ, що запалює, швидко повертається до результатів , але ви не хочете зберігати конкретний результат, до якого користувач перейшов.
тл; д-р
Потрібно мати клас, який реалізує RouteReuseStrategyта надає свою стратегію в ngModule. Якщо ви хочете змінити, коли маршрут зберігається, змініть shouldDetachфункцію. Коли він повертається true, Angular зберігає маршрут. Якщо ви хочете змінити, коли маршрут додається, змініть shouldAttachфункцію. Коли shouldAttachповернеться вірно, Angular буде використовувати збережений маршрут замість запитуваного маршруту. Ось вам Plunker, з яким ви можете пограти.
Про RouteReuseStrategy
Задавши це запитання, ви вже розумієте, що RouteReuseStrategy дозволяє сказати Angular не знищувати компонент, а насправді зберегти його для повторного візуалізації в більш пізній термін. Це здорово, тому що він дозволяє:
- Зменшення кількості дзвінків на сервері
- Підвищена швидкість
- І компонент переводить за замовчуванням у той самий стан, який він залишився
Останнє є важливим, якщо ви хочете, скажімо, залишити сторінку тимчасово, навіть якщо користувач ввів у неї багато тексту. Підприємницькі програми будуть любити цю функцію через надмірну кількість форм!
Це те, що я придумав, щоб вирішити проблему. Як ви сказали, вам потрібно скористатисяRouteReuseStrategy запропонованим @ angular / router версією 3.4.1 і вище.
РОБИТИ
Перший переконайтеся, що у вашого проекту @ кутова / маршрутизатор версії 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 , він фактично повторно використовує маршрут, на якому ви зараз перебуваєте, і жоден з інших методів не запускається. Я просто повертаю помилкове, якщо користувач пересувається.
- Якщо
shouldReuseRouteповертається false, shouldDetachпожежі. shouldDetachвизначає, чи хочете ви зберігати маршрут, чи повертає booleanвказівник стільки ж. Тут ви повинні вирішити зберігати / не зберігати шляхи , що я б зробив, перевіривши масив шляхів, до яких потрібно зберегти route.routeConfig.path, і повернути помилкове, якщоpath в масиві не існує.
- Якщо
shouldDetachповертається true, storeобпалюють, який є можливість зберігати будь-яку інформацію ви хотіли б про маршрут. Що б ви не робили, вам потрібно буде зберігати, DetachedRouteHandleтому що саме Angular використовує, щоб згодом ідентифікувати ваш збережений компонент. Нижче я зберігаю як DetachedRouteHandleі ActivatedRouteSnapshotперемінну локальну для мого класу.
Отже, ми бачили логіку зберігання, а як щодо переходу до компонента? Як Angular вирішує перехопити вашу навігацію та поставити збережену на її місце?
- Знову ж таки, після того, як
shouldReuseRouteповернувся false, shouldAttachзапускається, що є вашим шансом з’ясувати, чи хочете ви відновити чи використовувати компонент у пам'яті. Якщо ви хочете повторно використовувати збережений компонент, поверніться trueі ви вже на шляху!
- Тепер Angular запитає вас, "який компонент ви хочете, щоб ми використовували?", Який ви вкажете, повернувши цей компонент
DetachedRouteHandleз retrieve.
Це майже вся логіка, яка вам потрібна! У коді reuse-strategy.tsнижче, я також залишив вам чудову функцію, яка буде порівнювати два об'єкти. Я використовую його для порівняння майбутнього маршруту 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;
}
}
Поведінка
Ця реалізація зберігає кожен унікальний маршрут, який користувач відвідує на маршрутизаторі рівно один раз. Це продовжуватиме додавати до компонентів, що зберігаються в пам'яті протягом усього сеансу користувача на сайті. Якщо ви хочете обмежити маршрути, які ви зберігаєте, місце це зробити - це shouldDetachметод. Він контролює, які маршрути ви збережете.
Приклад
Скажіть, що ваш користувач шукає щось з домашньої сторінки, що перенаправляє їх до шляху search/:term, що може виглядати так www.yourwebsite.com/search/thingsearchedfor. Сторінка пошуку містить купу результатів пошуку. Ви хочете зберегти цей маршрут, якщо вони захочуть повернутися до нього! Тепер вони натискають на результат пошуку і переходять до них view/:resultId, які ви не хочете зберігати, бачачи, що вони, ймовірно, будуть там лише один раз. Маючи вищезазначене впровадження, я просто змінив би 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 зберігатиме лише один екземпляр маршруту, це сховище буде легким, і ми будемо зберігати лише компонент, розташований у, search/:termа не всі інші!
Додаткові посилання
Хоча там ще мало документації, ось кілька посилань на те, що існує:
Кутові документи: 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
Реалізація RouteReuseStrategy за замовчуванням nativescript-angular : https://github.com/NativeScript/nativescript-angular/blob/cb4fd3a/nativescript-angular/router/ns-route-reuse-strategy.ts