代码之家  ›  专栏  ›  技术社区  ›  3gwebtrain

如何在初始化DOM和数据之前重定向到主页?

  •  3
  • 3gwebtrain  · 技术社区  · 6 年前

    我有3页,第2页将数据提供给第3页。它工作得很好。问题是当用户刷新第3页时,我想导航主页。因为第3页没有可用数据。

    我试着这样做:

    constructor(private store: StorageService, 
          private sharedData: SharedDatasService, 
          private location:Location,
          private route:Router) {
    
          console.log('this.sharedData.validationDatas', this.sharedData.validationDatas );
    
          if(Object.keys(this.sharedData.validationDatas).length === 0 ) { //there is not data.. go to home.
              this.route.navigate(['']);
              return;
          }
    
        }
    

    但我还是从中得到了错误 DOM 编译。我的页面根本没有重定向到主页…

    如何处理?

    我得到的错误:

    TypeError: Cannot read property 'book.label.title.packageSizes' of undefined
    
    2 回复  |  直到 6 年前
        1
  •  1
  •   Eldho    6 年前

    您可以使用路线警卫来实现这一点。

    在你的 路由配置

    const routes: Routes = [
    { path: 'secondPage', component: SecondPage},
      {
        path: 'thridpage',
        component: ThridPage,
        canActivate: [DataCheckRouteGuard],
      }
    ];
    

    数据检查路由保护

    import { CanActivate } from '@angular/router';
    import { Injectable } from '@angular/core';
    import { sharedData} from './SharedDatasService';
    
    @Injectable()
    export class DataCheckRouteGuard implements CanActivate {
    
      constructor(private sharedData: SharedDatasService) {}
    
      canActivate() {
      if(this.sharedData.validationDatas!==undefined) 
       {
         return true;
       } else 
       {
       // No data so navigate to second page
        this.router.navigate(['/secondPage'] 
    
        return false
       }
      }
    }
    

    Usage of routes

        2
  •  1
  •   3gwebtrain    6 年前

    我按条件更改了HTML标签,现在可以正常工作了。

    更新如下:

    它是:

    {{getLabel('book.label.title.packageSizes')}}
    

    现在是:

    {{getLabel('book?.label.title.packageSizes')}}