使用角度2

时间:2017-02-09 08:28:01

标签: javascript angular angular2-routing

我对angular 2非常新。我正在尝试使用Login和Dashboard Pages构建一个简单的应用程序。我需要了解如何应用路由作为我的应用程序需要。

登录页面是一个独立的路由配置,但我想在使用登录时,新的仪表板页面附带导航栏和它自己的<router-outlet>

const routes: Routes = [
    { path: '', redirectTo: 'login', pathMatch: 'full' },
    { path: 'login', component: LoginComponent },
    { path: 'register-user', component: RegisterUserComponent },
    //APPLICATION ROUTES WITH OWN <router-outlet>
    { path: '**', redirectTo: 'login' }
]

在角度1的早期,我们使用了具有抽象状态和子状态的ui-router。

请建议我们如何做到这一点。

3 个答案:

答案 0 :(得分:0)

工作plunkr

https://maven.apache.org/guides/introduction/introduction-to-the-pom.html

创建一个ContainerComponent&amp;它应该拥有自己的路由器插座和放大器。 routerLinks。

默认情况下,始终使用redirectTo

加载到任何组件
{ path: 'component-two', component: ComponentTwo,
    children: [
      { path: '', redirectTo: 'child-one', pathMatch: 'full' },
      { path: 'child-one', component: ChildOne },
      { path: 'child-two', component: ChildTwo }
    ]
  }

答案 1 :(得分:0)

假设你在主模块中有一个子模块。
所以App模块和登录子模块

submodule

主模块的目录结构

main module directory

app.routing.module.ts 看起来像这样

import os
import time
import threading
from concurrent.futures import ThreadPoolExecutor
from tornado.ioloop import IOLoop
from tornado.queues import Queue


def read_file(file_path, queue: Queue, io_loop: IOLoop, chunk_size: int = 64 * 1024):
    file_size = os.path.getsize(file_path)
    remaining = file_size
    fin = open(file_path, "rb")
    lock = threading.Lock()

    def putter(chunk, lock: threading.Lock):
        queue.put(chunk)        # Called from the loop's thread -> can block
        lock.release()          # Awake reader thread after the chunk has been put into the processing queue

    def put(chunk, lock):
        """Put the chunk into the queue, and wait until it is processed by the ioloop"""
        lock.acquire()  # Acquire in this thread
        io_loop.spawn_callback(putter, chunk, lock) # Release in the loop's thread
        lock.acquire()  # Wait until the loop's thread has accepted the chunk for processing
        lock.release()  # Cleanup before return

    # Put the file size into the queue without waiting
    io_loop.spawn_callback(queue.put, file_size)

    while remaining > 0:
        chunk = fin.read(min(chunk_size, remaining))
        print("read", chunk)
        remaining -= len(chunk)
        time.sleep(1)  # Just for testing: simulate slow file reads.
        put(chunk, lock)

    # Put EOF/terminator into the queue
    io_loop.spawn_callback(queue.put, None)


pool = ThreadPoolExecutor(3)


async def main():
    # Create a queue for sending chunks of data
    cq = Queue(maxsize=3)
    # Start the reader thread that reads in a separate thread
    pool.submit(read_file, __file__, cq, io_loop, 100)
    file_size = await cq.get()
    print("file size:", file_size)
    # Process chunks
    while True:
        item = await cq.get()
        # Terminator -> EOF
        if item is None:
            break
        print("got chunk:", repr(item))

    io_loop.stop()


if __name__ == '__main__':
    io_loop = IOLoop.current()
    io_loop.run_sync(main)
    io_loop.start()

和相应的 的 login.routing.module.ts

export const routes: Routes = [
  { path: '', component:LoginComponent, pathMatch: 'full'},
   { path: Constants.LOGINROUTE, component:LoginComponent, pathMatch: 'full'}
  ];

@NgModule({
  imports: [RouterModule.forRoot(routes,{ useHash: true })],
  exports: [RouterModule]
})

dashboard.routing.module.ts 将如下所示

@NgModule({
  imports: [RouterModule.forChild([
    { path: Constants.LOGINROUTE, component: LoginComponent}
  ])],
  exports: [RouterModule]
})
export class LoginRoutingModule {}

correspoding包括login.module.ts中的login.routing.module.ts和dashboard.routing.module.ts中的相同

答案 2 :(得分:0)

我在我的项目中完成了这项工作。

这用于子路由的延迟加载:

您应该在主loadChildren中使用app-routing.module.ts

{ path: 'crisis-center',
  loadChildren: 'app/modules/crisis-center/crisis.module#CrisisCenterModule'
 },   

然后从以下代码中的component中删除app-module.ts file

app.module.ts:

@NgModule({
      imports: [ RouterModule.forRoot(routes, { useHash: true })
        // ,AdminModule 
       ],
      declarations: [ ],
      providers: [ ],
      bootstrap: [ AppComponent ]
    })

应用-routing.module.ts:

export const routes: Routes = [
  { path:  'dashboard',                  component: DashboardComponent },
  { path: 'admin',
    loadChildren: 'app/admin/admin.module#AdminModule'
  },
  { path: 'crisis-center',
    loadChildren: 'app/modules/crisis-center/crisis.module#CrisisCenterModule'
  },
  { path:  '', redirectTo: '/dashboard', pathMatch: 'full' },
  { path:  '**',                         component: PageNotFound},

];

现在很好。当router导航到此路线时,它会使用loadChildren字符串动态加载AdminModule。然后,它将AdminModule路由添加到其当前路由配置。最后,它将请求的路由加载到目标管理组件。

您也可以在routing文件中使用此(children []),并为每个子路径提供单独的组件:

const crisisCenterRoutes: Routes = [
  {
    path: '',
    component: CrisisCenterComponent,
    children: [
      {
        path: '',
        component: CrisisListComponent,
        children: [
          {
            path: ':id',
            component: CrisisDetailComponent,
            canDeactivate: [CanDeactivateGuard]
          },
          {
            path: '',
            component: CrisisCenterHomeComponent
          }
        ]
      }
    ]
  }
];

然后将所有组件添加到您的特定module.ts文件中,如下所示:

import { NgModule                   }       from '@angular/core';
import { CommonModule               }       from '@angular/common';
import { FormsModule                }       from '@angular/forms';
import { CrisisCenterRoutingModule  }       from './crisis-center-routing.module';
import { CrisisCenterComponent      }       from './crisis-center.component';
import { CrisisListComponent        }       from './crisis-list.component';
import { CrisisDetailComponent      }       from './crisis-detail.component';
import { CrisisCenterHomeComponent  }       from './crisis-center-home.component';
import { CrisisService              }       from './crisis.service';

 @NgModule({
  imports: [ CommonModule,CrisisCenterRoutingModule,FormsModule, ],
  declarations: [CrisisCenterComponent ,CrisisListComponent,CrisisDetailComponent,CrisisCenterHomeComponent ],
  providers: [ CrisisService ],
})

export class CrisisCenterModule {}