为什么当我键入特定的URL(带有ID参数)时,该页面无法正常工作,并引发错误“未捕获的ReferenceError:未定义系统”?

杜诺万特

这是我的“ app.routing.ts”:

import {provideRouter, RouterConfig} from "@angular/router";

import {DashboardComponent} from "./dashboard.component";
import {HeroesComponent} from "./heroes.component";
import {HeroDetailsComponent} from "./hero-details.component";

export const routes: RouterConfig = [
    {path: '',            component: DashboardComponent },
    {path: 'dashboard',   component: DashboardComponent },
    {path: 'heroes',      component: HeroesComponent },
    {path: 'details/:id', component: HeroDetailsComponent }
];

export const APP_ROUTER_PROVIDERS = [
    provideRouter(routes)
];

这是我要加载键入url的页面:

import {Component, OnInit}  from "@angular/core";
import {Router, ActivatedRoute} from "@angular/router";

import {Hero}       from "./hero.class";
import {HeroService} from "./hero.service";

@Component({
    selector    : "my-hero-details",
    template    : `
        <div *ngIf="myhero">
            <h2>{{myhero.name}} details!</h2>
            <div><label>id: </label>{{myhero.id}}</div>
            <div>
                <label>name: </label>
                <input id="heroname" [(ngModel)]="myhero.name" placeholder="name">
            </div>
      </div>
      <button (click)="goBack()">Back</button>
    `,
    providers   : [HeroService]
})

export class HeroDetailsComponent implements OnInit{

    myhero:Hero;
    sub:any;

    ngOnInit(){
        this.getHeroDetails();
    }

    ngOnDestroy(){
        this.sub.unsubscribe();
    }

    constructor(private heroService:HeroService, private router:Router, private route:ActivatedRoute){}

    getHeroDetails(){

       this.sub = this.route.params.subscribe((param)=>{
           let id:number = +param["id"];
           //let id:number = +this.route.snapshot.params["id"];
           this.heroService.getHero(id).then((hero)=>{
               this.myhero = hero;
           });

        });

    }

    goBack(){
        window.history.back();
    }

}

我的问题是当我输入网址“ ... / details / 12” 12作为ID时,但是如果到达该页面,请单击下面触发该按钮的按钮,即可正常工作

this.router.navigate(["/details", this.selectedHero.id]);

我没有使用任何服务器,或者实际上我正在使用Angular2 QuickStart中的“ system.config.js”,也许这就是问题所在“未捕获的ReferenceError:未定义系统”。

加比

在服务器端,您应该默认/映射404路由(基本上是为了与您的angular2应用程序可能的路由匹配)到您的angular2盯着html(也许是index.html)

UPDATE1:

如果使用lite-server,则如果路由不匹配,则应返回默认的index.html:

创建SPA时,存在仅浏览器知道的路由。例如,/ customer / 21可能是Angular应用程序的客户端路由。如果此路由是手动输入的或直接链接为Angular应用程序的入口(也称为深层链接),则静态服务器将收到请求,因为尚未加载Angular。服务器将找不到该路由的匹配项,因此将返回404。在这种情况下,所需的行为是返回index.html(或我们定义的应用程序的任何起始页)。BrowserSync不会自动允许后备页面。但是它确实允许自定义中间件。这是lite-server介入的地方。lite-server是BrowserSync周围的一个简单的自定义包装器,可轻松提供SPA。

检查cli参数“ --entry-file = PATH”(这应该为特定文件提供此服务,而不是缺少路由):

live-server --entry-file=index.html

还要查看以下问题:Angular 2.0路由器无法重新加载浏览器

您还可以使用本地bs-config.json或bs-config.js文件配置高级行为。

有关更多详细信息:https : //www.npmjs.com/package/lite-server

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章