在解析数据之前,Angular路由不会导航到路由

时间:2017-03-25 09:14:52

标签: javascript angular typescript angular2-routing

我有一个简单的网页应用,其中包含详细信息页面。当最终用户单击链接时,路径会导航到该页面,直到页面上的数据准备就绪。理想情况下,我想立即显示页面并相应地更新UI。我做错了什么吗?请查看我的内容。

在我的路线档案中

import { Routes } from '@angular/router';
import { DetailsComponent } from './details/details.component';

export const AppRoutes:Routes = [
 { path: 'details/:id', component: DetailsComponent },
 { path: '', redirectTo:'/home', pathMatch: 'full' }
]

查看点击链接的位置以导航至详细信息

<div *ngFor="let data of privateInfo; let i = index">
      <span>{{i}}</span>
      <span><a [routerLink]="['/details', i]">Review Details</a></span>
</div>

明细组件

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { PrivateModel } from '../models/app-model';

@Component({
  selector: 'app-details',
  template: `
    <div>
     <pre>{{ privateInfo }}</pre>
    </div>
  `
})
export class DetailsComponent implements OnInit {
public privateInfo:Array<any>;
public detailID;

constructor(public PrivateModel:PrivateModel, private    route:ActivatedRoute) {
  this.detailID = route.snapshot.params['id'];
}

ngOnInit() {
  this. privateInfo = this.PrivateModel[this.detailID];
}
}

查看Angular文档似乎有一个noPreloading类但不确定如何利用它。任何帮助和/或额外的一组眼睛将不胜感激。

1 个答案:

答案 0 :(得分:0)

您应该在路线定义中使用resolve属性,如下所示,

export const AppRoutes:Routes = [
     { path: 'details/:id', component: DetailsComponent ,resolve: {details: DetailsResolver} },
     { path: '', redirectTo:'/import', pathMatch: 'full' }
]

您的DetailsResolver服务必须如下

import { Injectable }             from '@angular/core';
import { Router, Resolve, RouterStateSnapshot,
         ActivatedRouteSnapshot } from '@angular/router';
import { DetailsService } from '....';
@Injectable()
export class DetailResolver implements Resolve<Details> {
  constructor(private cs: DetailsService, private router: Router) {}
  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<Details> {
    let id = route.params['id'];
    return this.cs.getDetails(id).then(details => {
      if (details) {
        return details;
      } else { // id not found
        this.router.navigate(['/error']);
        return null;
      }
    });
  }
}