Router named outlets that are activated once

前端 未结 4 638
孤城傲影
孤城傲影 2021-01-17 18:11

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 t

4条回答
  •  没有蜡笔的小新
    2021-01-17 18:25

    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).

提交回复
热议问题