【问题标题】:Using a service to define routes in Angular2 and TypeScript使用服务在 Angular2 和 TypeScript 中定义路由
【发布时间】:2016-06-03 11:09:14
【问题描述】:

Angular2 路由器没有输出所有路由的方法,所以我所做的是定义一个服务来输出这样的路由...

export class Route {
        constructor(
            public path: string,
            public component: any
        ) {}
    }

    @Injectable()
    export class RouteService {

        public static getRoots(): Route[] {
            return [
                 { path: '/', component: HomeComponent },
                { path: '/about-me', component: AboutMeComponent },
                { path: '/food', component: FoodComponent },
                { path: '/photos', component: PhotosComponent },
                { path: '/technology', component: TechnologyComponent },
                { path: '/blog', component:BlogComponent }
            ];
        }
    }

现在我在我的main.ts 中使用它,就像@Routes(RouteService.getRoots()) 一样,一切似乎都正常,但是我想使用相同的服务来定义一个变量,这样我就可以循环遍历路由数组......就像这样

export class NavigationComponent {

    public routes: Route[];

    constructor(private router:Router, private routeService: RouteService) {

       // just write this to the console for now
       console.log(routeService.getRoots());
    }

    // more code here, etc....

但是,这会在控制台routeService.getRoots is not a function 中产生错误,并且我的应用程序崩溃了!我必须做什么才能在 main.ts 的 @Routes() 部分使用该服务,同时在其他组件中使用该服务。我真的不知道我哪里错了,因为 Angular2 现在正在改变我的想法!

【问题讨论】:

    标签: typescript angular


    【解决方案1】:

    因为getRoots() 方法被标记为静态。如果你需要它是静态的,你必须这样称呼它:RouteService.getRoots()。否则,只需删除 static 关键字即可。


    编辑: @Routes() 部分中没有您的服务实例,因此您需要一个静态方法。由于您所做的只是调用一个静态方法,因此您也无需再将其注入构造函数中。

    【讨论】:

    • 如果成员是静态的,那么注入它是没有意义的。
    • 但是,当我删除 statickeyword 时,我会在 main.ts - routes_1.RouteService.getRoots is not a function(…) 中出错,因此我无法在 main.ts 的 @Routes() 部分中使用该服务
    • 如果您删除了static 关键字,您必须使用您的实例routeService.getRoots() 调用该方法。但另一方面,我猜您在 @Routes() 部分中没有该类的实例。
    猜你喜欢
    • 2017-04-22
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-30
    • 2018-07-03
    • 1970-01-01
    相关资源
    最近更新 更多