父路径为空的Angular Named Router Outlet

时间:2018-02-22 13:16:16

标签: angular

设定:

版本:5.2.1

错误消息

  

未捕获(承诺):错误:无法匹配任何路线。网址细分:'loginpopup'

此问题似乎与以下行有关:

this._router.navigate([{ outlets: { login: ['loginpopup'] } }], { relativeTo: this.route });

我尝试使用以下内容但仍然没有看到:

this._router.navigate([{ outlets: { login: ['loginpopup'] } }]);

this._router.navigate(['/', { outlets: { login: ['loginpopup'] } }]);

this._router.navigate(['/', '' ,{ outlets: { login: ['loginpopup'] } }]);

问题与在根级别将父路径设置为''(请参阅下面的代码)将shell组件的路径更改为“任何”并将代码更改为:

this._router.navigate(['/', 'anything' ,{ outlets: { login: ['loginpopup'] } }]);

我能够成功使用指定的插座。

代码

App.routings.ts

export const appRoutes: Routes =
[
    // Primary Routes
    {
        path: '',
        component: ShellComponent,
        data:
        {
            WebsiteTitle: 'Core'
        },
        children:
        [
            {
                path: 'loginpopup',
                outlet: 'login',
                component: LoginComponent,
            },
            {
                path: 'login',
                component: LoginComponent,
                children: [

                ]
            }
        ]
    }
]

App.component

<router-outlet></router-outlet>
<router-outlet name="dialog"></router-outlet> 

Shell.component.html

<main class="applicationcontainer m-0 animated fadeIn" [ngClass]="{'mt-5 pt-4': !isLogin}">
    <div class="container-fluid p-0">
        <router-outlet name="login"></router-outlet>
        <router-outlet></router-outlet>
    </div>
</main>

Shell.component.ts

import {
  Component,
  ChangeDetectionStrategy,
  ChangeDetectorRef
} from "@angular/core";
import { Router, ActivatedRoute } from "@angular/router";
import { Observable } from "rxjs/Observable";
import { Subject } from "rxjs";
import { AutoUnsubscribe } from "ngx-auto-unsubscribe";
import {
  AuthenticationEventService,
  AuthSessionStorageService
} from "interpackages/secure";
import { relative } from "path";

/**
 *
 *
 * @export
 * @class ShellComponent
 */
@Component({
  templateUrl: "shell.component.html",
  selector: "shell",
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class ShellComponent {
  public isLogin: boolean = false;

  /**
   *
   * Creates an instance of ShellComponent.
   * @param {Router} _router
   * @param {ChangeDetectorRef} changeRef
   * @memberof ShellComponent
   */
  constructor(
    private _authenticationEventService: AuthenticationEventService,
    private changeRef: ChangeDetectorRef,
    private _autSessionStorage: AuthSessionStorageService,
    private _router: Router,
    private route: ActivatedRoute,
  ) {
    this.isLogin = this._autSessionStorage.AuthenticationInfo.IsSignedIn;
    if (!this.isLogin) {
       this._router.navigate([{ outlets: { login: ['loginpopup'] } }], { relativeTo: this.route });
    } else {
      this._router.navigate(['/', { outlets: { login: null } }]);
    }

    this._authenticationEventService.AuthenticationInfo.subscribe(authUser => {
      this.isLogin = authUser.IsSignedIn;
      if (!authUser.IsSignedIn) {
        this._router.navigate(['/',{ outlets: { login: ['loginpopup'] } }]);
      } else {
        debugger;
        this._router.navigate([{ outlets: { login: null } }]);
      }
      this.changeRef.detectChanges();
    });
  }

  /**
   * For when component is destoried. Also Requied for  AutoUnsubscribe to work on AOT Build
   * @memberof ShellComponent
   * @method ngOnDestory
   *
   */
  ngOnDestroy() {}
}

2 个答案:

答案 0 :(得分:0)

不幸的是,角度github存储库中有一个关于此问题的问题,https://github.com/angular/angular/issues/10726

您可以做的唯一工作是命名基本路径,即

export const appRoutes: Routes = [ {
   path: 'myroute', // NO Longer Empty Path
   component: ShellComponent,
   data:  { WebsiteTitle: 'Core' },
   children: [  ...  ]
}];

答案 1 :(得分:0)

找到角度标准的解决方法:

与空路由器插座有关的问题。您还需要知道相对路径仅相对于路由器树(ActiveRoutes)而不是URL。考虑到这一点,我已经创建了一个辅助函数来解决问题,直到它在Angular 6.1中修复

import { Router, ActivatedRoute } from '@angular/router';
/**
 *
 * Angular Relative path tempory solution. Angular doesn't like empty paths.
 * Should be fixed in version 6 Pull request 22394
 * https://github.com/angular/angular/pull/22394
 *
 * Angular Issue: https://github.com/angular/angular/issues/13011#issuecomment-274414952
 *
 * Before removing check relative paths work on named outlet. Using Navigate on named
 * outlet currently relates to secondary routes (outlet:'route/test)
 * this meant breaking out wasn't possiable using ../../ like documented in
 * angular own documentation
 *
 * key Information: This is relative to routes like anuglar intended NOT URL path
 *
 * Bug only relates to going to parent and down the tree
 *
 * @export NavigateByRelative
 * @param {string} path
 * @param {Router} router
 * @param {ActivatedRoute} route
 *
 */
export function NavigateByRelative(path: string, router: Router, route: ActivatedRoute) {

    /**
     * Relative paths should always start with '../' as per angular documentation
     * https://angular.io/guide/router#relative-navigation
     */
    if (path.startsWith('../')) {
        // split path into multiple paths
        const paths = path.split('/');

        // minus 1 on length as we gurantee need the last index
        const totalPathToLastIndex = paths.length - 1;

        // current index so we can start at this later on
        let currentPathIndex;

        // Relative to is so we get to the correct parent
        let relativeTo = route;

        // Check their is a parent and the current path still intended to go back up the tree
        for (currentPathIndex = 0;
            currentPathIndex < totalPathToLastIndex
            && relativeTo.parent !== undefined
            && paths[currentPathIndex] === '..';
            currentPathIndex++
        ) {
            relativeTo = relativeTo.parent;
        }

        // Navigate starting at the the currentpathIndex and relative to the current parent
        router.navigate([...paths.splice(currentPathIndex )], { relativeTo });

    } else {
        // else use navigation as normal as this should work correctly
        router.navigate([path]);
    }
}