Angular router 3 routerLink无法正常工作

时间:2016-07-22 16:00:21

标签: angular

我正在使用Angular 2.0.0-rc3和路由器3.0.0-alpha.8。

我有一个BookListComponent,其中包含以下模板:

<nav>
  <a routerLink="/new-book">New Book</a>
</nav>

<ul>
  <li *ngFor="let book of books">{{ book.name }}</li>
</ul>

然后是BookListComponent本身:

import { Component, OnInit } from '@angular/core';
import { BookService } from '../book.service';
import { ROUTER_DIRECTIVES } from '@angular/router';

@Component({
  moduleId: module.id,
  selector: 'app-book-list',
  templateUrl: 'book-list.component.html',
  styleUrls: ['book-list.component.css'],
  providers: [ROUTER_DIRECTIVES, BookService]
})
export class BookListComponent implements OnInit {
  books: any;

  constructor(private bookService: BookService) {}

  ngOnInit() {
    this.bookService.getList()
      .subscribe(response => this.books = response.json());
  }

}

链接不仅没有带我到/new-book路线(如果手动访问“,工作得很好),但”链接“甚至不是链接 - 它只是黑色文本。

如何让链接生效?

2 个答案:

答案 0 :(得分:2)

我在ROUTER_DIRECTIVES下有providers,但它必须位于directives之下。将其移至directives可解决问题。

这是我的新BookListComponent

import { Component, OnInit } from '@angular/core';
import { BookService } from '../book.service';
import { ROUTER_DIRECTIVES } from '@angular/router';

@Component({
  moduleId: module.id,
  selector: 'app-book-list',
  templateUrl: 'book-list.component.html',
  styleUrls: ['book-list.component.css'],
  providers: [BookService],
  directives: [ROUTER_DIRECTIVES]
})
export class BookListComponent implements OnInit {
  books: any;

  constructor(private bookService: BookService) {}

  ngOnInit() {
    this.bookService.getList()
      .subscribe(response => this.books = response.json());
  }

}

答案 1 :(得分:0)

检查您是否错过了主机视图HTML中的Router Outlet标记。

<router-outlet></router-outlet>

我用它作为参考:
https://angular.io/docs/ts/latest/guide/router.html