Router named outlets that are activated once

∥☆過路亽.° 提交于 2019-12-04 03:01:35

问题


Is it possible to have router named outlets that are activated once and then never destroyed, no matter what route is navigated in primary outlet?

The intention is to have components that persist on page (for instance, sidebar) but get the benefits of routing on their initial load - such as guards (resolvers) and lazy loading.

The requirement is that named outlets shouldn't affect UX in any negative way, for example by introducing garbage suffixes to SPA URL, e.g. (outletName:routeName), they also shouldn't be accidentally deactivated. If there's a way to detach them from router after initial activation, it would be appropriate.

skipLocationChange option cannot be used for this purpose. In this example /login(popup:compose) URL appears when Contact and Login routes are sequentially navigated.


回答1:


Router needs information about named outlets, so there are good chances that implementing your own UrlSerializer will help.

Idea is simple, deserialization process should be aware of routes which have static named outlets and produce UrlTree which contains named outlets i.e. for /login url should produce the same UrlTree as default serializer will produce for url /login(popup:compose). During serialization static named outlet parameters should not be included into resulting url.




回答2:


It appears that we cannot use a secondary route that targets a named outlet without having the secondary route appended to the URL. As suggested in your question, one possible solution would be to detach the component from the router outlet once it has been activated. My attempt to implement that solution is shown in this stackblitz:

<router-outlet name="popup" #popupRouterOutlet (activate)="processActivate($event)"></router-outlet>
<ng-container #popupContainer></ng-container>
export class AppComponent {

  @ViewChild("popupRouterOutlet", { read: ViewContainerRef }) private popupRouterOutlet: ViewContainerRef;
  @ViewChild("popupContainer", { read: ViewContainerRef }) private popupContainer: ViewContainerRef;

  constructor(public router: Router) {
  }

  processActivate(e) {
      let viewRef = this.popupRouterOutlet.detach(0);
      this.popupContainer.insert(viewRef);
      this.router.navigate([".", { outlets: { popup: null } }]);
  }
}

In the activate event handler, the component is detached from the router outlet, it is inserted in an ng-container, and the router outlet is cleared. The component can then stay in the DOM, without using the secondary route anymore.

The static content of the component is tranferred successfully but, unfortunately, the bindings are not. That problem has already been reported. A request has been made on Angular Github in issue 20824, to allow moving a component from one container to another. Until that feature request is implemented, that kind of transfer doesn't seem to be possible.




回答3:


skipLocationChange navigation option works only for a router it was supplied for, then named outlet appears in the url, like /login(foo:bar).

It's possible to have permanent foo router outlet by overriding UrlSerializer, as was suggested by @kemsky:

import {
  UrlSerializer, DefaultUrlSerializer, UrlSegmentGroup, UrlTree
} from '@angular/router';

export class FooUrlSerializer extends DefaultUrlSerializer {
  serialize(tree) {
    const { foo, ...noFooChildren } = tree.root.children;
    const root = new UrlSegmentGroup(tree.root.segments, noFooChildren);
    const noFooTree = Object.assign(new UrlTree(), tree, { root });

    return super.serialize(noFooTree);
  }
}

...
providers: [{ provide: UrlSerializer, useClass: FooUrlSerializer }, ...]
...



回答4:


We encountered the same (crucial) UX requirement in our project and came up with a semi-clean but so far fully functional solution.

Implement a custom LocationStrategy, we simply extend the default PathLocationStrategy class and preprocess the URL (that will be presented to the user / browser):

@Injectable()
export class OnlyPrimaryLocationStrategy extends PathLocationStrategy implements LocationStrategy {
  static readonly AUX_ROUTE_SEPERATOR = '//';

  replaceState(state: any, title: string, url: string, queryParams: string): void {
    super.replaceState(state, title, this.preprocessUrl(url), queryParams);
  }

  pushState(state: any, title: string, url: string, queryParams: string): void {
    super.pushState(state, title, this.preprocessUrl(url), queryParams);
  }

  preprocessUrl(url: string): string {
    if (url.includes(OnlyPrimaryLocationStrategy.AUX_ROUTE_SEPERATOR)) {
      if (url.split(OnlyPrimaryLocationStrategy.AUX_ROUTE_SEPERATOR).length > 2) {
        throw new Error(
          'Usage for more than one auxiliary route on the same level detected - please recheck imlementation'
        );
      }
      return url.split(OnlyPrimaryLocationStrategy.AUX_ROUTE_SEPERATOR)[0].replace('(', '');
    } else {
      return url;
    }
  }
}

Do not forget to provide it in your module:

providers: [
    {
     // ...
      provide: LocationStrategy,
      useClass: OnlyPrimaryLocationStrategy,
    },
  ],

String processing obviously is not a 100% clean, but it gets the job done for us - maybe it helps you. Be aware that your URL is now not fully capable of reconstructing your router state (obviously).



来源:https://stackoverflow.com/questions/48836207/router-named-outlets-that-are-activated-once

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!