路由器 - 无法设置默认路由

时间:2016-03-05 06:28:23

标签: angular angular2-routing angular2-directives

以下代码不会自动显示列表,我必须创建一个链接并单击。有人可以帮忙吗?

谢谢

import { Component } from 'angular2/core';
import { HTTP_PROVIDERS } from 'angular2/http';
import { CourseListComponent } from '../lists/course.list';
import {RouteConfig, ROUTER_DIRECTIVES, ROUTER_PROVIDERS, LocationStrategy, HashLocationStrategy} from 'angular2/router';
import EndPointService  from '../../Services/EndPointService';
import {CourseDetailsComponent} from '../course.details';


@Component({
    selector: 'course-router-app',
    templateUrl: '/Admin/App/views/router/course-router-app.html',
    directives: [ROUTER_DIRECTIVES],
    providers: [
        HTTP_PROVIDERS,
        ROUTER_PROVIDERS,
        EndPointService
    ]
})
    @RouteConfig([
        { path: '/', name: 'Courses', component: CourseListComponent, useAsDefault: true },
        { path: '/details/:id', name: 'CourseDetails', component: CourseDetailsComponent }
])
export default class CourseRouterComponent {
}

课程列表组件

import { Component, View, OnInit } from 'angular2/core';
import { NgFor } from 'angular2/common';
import EndPointService  from '../../Services/EndPointService';
import LogService  from '../../Services/LogService';
import * as dtos from '../../view-models/ICourseViewModel';
import {Router, RouteParams} from 'angular2/router';

@Component({
    selector: 'course-list',
    providers: [EndPointService, LogService],
    templateUrl: '/Admin/App/views/lists/course-list.html'
})
export class CourseListComponent implements OnInit {
    public courses: dtos.ISimpleCourseViewModel[];

    constructor(private _endPointService: EndPointService, private _router: Router, private _logService: LogService) {

    }


    showDetails(course: dtos.ISimpleCourseViewModel) {
        this._logService.log('showing details ' + course.ID);
        this._router.navigate(['CourseDetails', { id: course.ID }]);
    }

    ngOnInit(): any {
        this._endPointService.getAllCoursesSimple().subscribe(
            (response) => {
                this.courses = this.courses = response.json();
            },
            (err) => {
                console.log(err);
            });

    }

    public diagnostic(): string {
        return JSON.stringify(this.courses);
    }
}

我也设置了<base href="/">

我没有添加观点,因为我认为它们并不重要。有人可以帮忙吗?我无法看到我的代码与在线提供默认路由的示例有何不同。

1 个答案:

答案 0 :(得分:2)

作为一个仅供参考,我使用以下代码解决了这个问题 - 这是一个小小的黑客:

constructor(private _router: Router) {  }

    ngOnInit(): any {
        this._router.navigate(['Courses']);
    }