我缺少什么,可以在Nativescript上使用路由器?

时间:2018-09-25 16:13:28

标签: angular2-routing nativescript angular2-nativescript

我正在尝试使用nativescript构建我的第一个应用程序。我正在浏览文档,但是不确定我丢失了什么,所以无法修复。

我具有以下结构:

- app
-- app-routing.module.ts
-- app.component.html
-- app.component.ts
-- app.css
-- app.module.ts
- home
-- home.component.css
-- home.component.html
-- home.component.ts
- restaurant
-- restaurant.component.css
-- restaurant.component.html
-- restaurant.component.ts

问题是,我试图做到这一点,以便当有人点击home.component.html中的元素时:

<Image class="h3 m-5" col="0" row="0" src="~/images/beet-logo.jpg" (tap)="visitRestaurant()" height="87" width="80"></Image>

它们被重定向到restaurant.component.html页。

我定义了如上所示的轻击事件,然后在home.component.ts上具有以下内容:

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

@Component({
    selector: "Home",
    moduleId: module.id,
    templateUrl: "./home.component.html",
    styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

    constructor(private router: Router) {
    }

    visitRestaurant() {
        this.router.navigate(["/restaurant"]);
    }

    ngOnInit(): void {
    }
}

当我单击它时,它失败,但出现错误:

  

错误错误:未捕获(承诺):错误:无法匹配任何路由。   网址段:“餐厅”

我曾考虑过在此处以及app-routing.module.ts中添加路线,但是每当尝试时,我都会得到cannot find name: RestaurantComponent。因此,我假设我需要将组件导出到某个地方,但不确定在哪里或如何导出。

你们能帮我吗?

如果有用,这是我的app-routing-module.ts

import { NgModule } from "@angular/core";
import { Routes } from "@angular/router";
import { NativeScriptRouterModule } from "nativescript-angular/router";

const routes: Routes = [
    { path: "", redirectTo: "/home", pathMatch: "full" },
    { path: "home", loadChildren: "./home/home.module#HomeModule" }
];

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

这是我的restaurant.component.ts代码:

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

@Component({
    selector: "Restaurant",
    moduleId: module.id,
    templateUrl: "./restaurant.component.html",
    styleUrls: ['./restaurant.component.css']
})
export class RestaurantComponent implements OnInit {

    constructor(private router: Router) {
    }

    ngOnInit(): void {
    }
}

1 个答案:

答案 0 :(得分:2)

您需要为/restaurant添加路线。例如,您可以这样做:

const routes: Routes = [
    { path: "", redirectTo: "/home", pathMatch: "full" },
    { path: "home", loadChildren: "./home/home.module#HomeModule" },
    { path: "restaurant", component: RestaurantComponent }
];

此外,您还需要确保导出/导入语句正确显示。

restaurant.component.ts内:

@Component({ ... })
export class RestaurantComponent { ... }

app-routing.module.ts内:

import { RestaurantComponent } from ' ... ';