如何修复在Angular Hybrid应用中添加的多个ng-view div?

问题描述 投票:0回答:1

我通过遵循Angular's Upgrade GuideViktor Savkin's Upgrade Series设置了AngularJS / Angular混合应用程序,以尝试迁移庞大的旧代码库。我已向该应用程序添加了一条新路线,该路线将使用Angular组件,并且正在使用新的Angular Router和AngularJS应用程序中的ngRoute一起使用。

一切正常(AngularJS模板中使用了Angular Component,并且一些新的URL完全在Angular Components上运行),除了这个小而烦人的问题-如果打开应用程序的主页,则无法使用任何托管的路由通过ngRoute以及由Angular Router管理的所有路由将继续显示主页模板。


这是代码的样子(来自项目根目录src目录的所有路径):

ng2 / app.component.html

<router-outlet></router-outlet>
<div ng-view></div>

ng2 / app.component.ts

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent {
   constructor(private upgrade: UpgradeModule) { }

    ngOnInit() {
      this.upgrade.bootstrap(document.documentElement, ['app']);
    }
}

ng2 / app.module.ts

declare var angular: any;

export class CustomHandlingStrategy implements UrlHandlingStrategy {
  shouldProcessUrl(url) {
    return url.toString().startsWith("/ng") || url.toString() == "/"
  }
  extract(url) { return url; }
  merge(url, whole) { return url; }
}

angular.module('app')
  .directive(
    'new-component',
    downgradeComponent({component: NewComponent})
  );

@NgModule({
  declarations: [
    AppComponent,
    Ng2DemoComponent
  ],
  imports: [
    BrowserModule,
    UpgradeModule,
    RouterModule.forRoot([
      {
        path: 'ng/newroute',
        component: NewComponent
      }
    ],
    {
      useHash: true,
      initialNavigation: true,
      enableTracing: true
    })
  ],
  entryComponents: [
    NewComponent
  ],
  providers: [
    { provide: UrlHandlingStrategy, useClass: CustomHandlingStrategy }
  ],
  bootstrap: [AppComponent]
})

export class AppModule {
}

ng1 / app.routes.js

var app = angular.module('app',[
  'ngRoute'
]);
app.config(['$routeProvider',function($routeProvider){
   $routeProvider
   .when('/', {
     templateUrl:'home/home.component.html'
   }).
   .when('/phone-list', {
     templateUrl:'phoneList/phoneList.component.html'
   });
}]);

index.html

<html lang="en">
     .
     .
     .
   <body ng-controller="rootController"> 
        <a href="#/phones"></a>
        <a routerLink="ng/newroute">New Component</a>
        <app-root></app-root>
     .
    </body>

打开应用程序的主页时,主页会正确呈现-但是跟随任何链接都会产生以下效果:

  • 如果链接指向旧的URL(在示例中为#/ phones),地址将在地址栏中更改,但不会呈现新的HTML。在任何此类链接上的每次点击都会附加一个新的<div ng-view>。在控制台中,显示错误消息Cannot read property 'nativeNode' of null
  • 如果链接指向新的URL(在示例中为ng / newroute),它将呈现预期的HTML,但是NOT隐藏home.component.html的标记。

从任何其他页面开始(例如,通过在地址栏中键入来直接访问#/ phones页面,每个链接都可以正常工作。

到目前为止已经尝试过的解决方案

  • 在一个或两个路由逻辑中添加一个宿路由-在两个路由逻辑中都执行此操作会完全停止另一个。

我想念什么吗?

angularjs angular angular-router ngroute ng-upgrade
1个回答
0
投票

您是否测试了以下内容?

代替

<router-outlet></router-outlet><div ng-view></div>

尝试

<router-outlet></router-outlet><div class="ng-view"></div>
© www.soinside.com 2019 - 2024. All rights reserved.