【问题标题】:Angular route does not navigate to route until data is resolved在解析数据之前,角度路由不会导航到路由
【发布时间】:2017-03-25 09:14:52
【问题描述】:

我有一个简单的网络应用程序,它有一个详细信息页面。当最终用户单击链接时,路由会导航到页面,直到页面上的数据准备好。理想情况下,我想立即显示页面并相应地更新 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 类,但不知道如何利用它。任何帮助和/或额外的一双眼睛将不胜感激。

【问题讨论】:

    标签: javascript angular typescript angular2-routing


    【解决方案1】:

    您应该在路由定义期间使用 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;
          }
        });
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-12-21
      • 2021-10-01
      • 2017-07-14
      • 2018-07-08
      • 2017-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-18
      相关资源
      最近更新 更多