账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    angular4+ 中动态路由的配置
    39
    0

    问题背景

    项目首页需要支持PC端和pad端访问,PC端和PAD端的页面设计图相差太远,基本上没办法用@media搞定。

    现在的情况

    我设想的解决办法是:在module文件中配置路由时,判断当前的浏览器是否为pad浏览器,代码如下:

    function isPad() {
        const ua = navigator.userAgent;
        return (ua.indexOf('Android') > 0 || ua.indexOf('iPhone') > 0 || ua.indexOf('iPad') > 0);
    }
    
    const routes: Routes = [];
    
    // 如果是pad浏览器,那么默认就加载Pad端首页
    if(isPad()) {
        routes.push({
            path: '',
            component: PadIndexComponent
        });
    } else {
         // 加载PC端首页
         routes.push({
            path: '',
            component: PcIndexComponent
        });
    }
    
    console.log('===>',routes);
    
    @NgModule({
        imports: [
            CommonModule,
            HttpClientModule,
            RouterModule.forChild(routes),
        ],
       .... 
    });
    

    问题

    在普通的开发模式下没有问题,AOT的过程中也没有问题,但是运行AOT之后的页面,结果页面一片白,查看了网页源代码,上面配置的2个组件都没有加载到页面中。Console中也没有任何错误,代码中的log方法正常调用。

    so. 有人遇到过这样的需求或者场景吗? 是如何解决的呢?

    0
    打赏
    收藏
    点击回答
        全部回答
    • 0
    • 一个人的旅行 普通会员 1楼

      在Angular4+中,我们可以使用动态路由配置来实现页面跳转的功能。以下是一个简单的例子:

      首先,我们需要在app.module.ts中添加动态路由配置:

      ```typescript import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router';

      const routes: Routes = [ { path: 'home', component: HomeComponent }, { path: 'about', component: AboutComponent }, { path: 'contact', component: ContactComponent } ];

      @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { } ```

      在上述代码中,我们创建了一个名为AppRoutingModule的模块,它包含了所有需要在路由中使用的路由。

      然后,我们需要在app.component.html中使用动态路由:

      html <a routerLink="/home">Home</a> <a routerLink="/about">About</a> <a routerLink="/contact">Contact</a>

      在这个例子中,当我们点击任何一个链接时,都会导航到相应的页面。

      此外,我们还可以在路由守卫中进行动态路由配置:

      ```typescript import { Router } from '@angular/router'; import { Injectable } from '@angular/core';

      @Injectable() export class DynamicRouterGuard { constructor(private router: Router) {}

      is资源配置正确() { // 在这里实现动态路由配置逻辑 return true; } } ```

      在上述代码中,我们创建了一个名为DynamicRouterGuard的守护服务,它使用路由器的is资源配置正确方法来检查资源配置是否正确。如果资源配置正确,它将返回true,否则返回false。

      这就是在Angular4+中使用动态路由配置的基本步骤。在实际使用中,你可能需要根据具体需求来配置路由和守护服务。

    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部