2017-05-04 60 views
0

我是Angular和Node JS的新手,我目前正在研究一个应用程序,当我决定如何在不同的组件之间进行最佳导航时,我想到了一个应用程序。Angular 2路径选项

Users are able to add the name of a user, and add books associated to that user

一旦点击一本书的名字,我希望导航到与书相关的部件,特别是拉动信息条目,如评论。

Component that will render specific book information

采用了棱角分明2(平均值堆栈),我想知道我应该如何解决这样一个问题 - 我应该存储任何特定的值,以方便两地浏览和拉有关的信息从数据库读书。

<article class="panel panel-default"> 
    <div class="panel-body"> 
      <div class="author"> 
       {{ author.fullName }} 
      </div> 
      <div class="addbook"> 
       <book-input [author]='author'></book-input> 
      </div> 
    </div> 
    <footer class="panel-footer"> 
     <div> 
      <ul *ngFor="let book of author.books"> 
       <li><a [routerLink]="['book']">{{ book }}</a></li> 
      </ul> 
     </div> 
    </footer> 
</article> 

任何建议将不胜感激

+0

我看不到你的截图链接它说'503'错误 – Aravind

+0

感谢您的来信,奇怪 - 我重新上传 –

+0

请尽量不要在同一个问题中标记Angular和Angularjs;尽管名称明显混乱,但它们是完全不同的框架。 – Claies

回答

0

我会做到这一点的方法是一个ID添加到您的路由器链路的末端,所以其路由到像书/ thebookid。

那么你还是你的路由模块中添加类似这样:

{path: 'book/:id, component: BookComponent} 

然后在你的书组件,你要寻找的URL该ID,并告诉它从取书你的服务。你会想要导入一些东西来实现它。

import {Router, ActivatedRoute, Params} from '@angular/router'; 

然后在你的构造函数,你必须实例化一些:

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

你实际上可能想导入“@角/核心”也的OnInit所以它运行所需的逻辑初始化组件。因此,将其添加到组件的顶部。

import {OnInit} from '@angular/core'; 

,确保您的组件实现它,当你把它声明

export class BookComponent implements OnInit {...} 

然后在你的组件,声明你ngOnInit方法,然后里面,你可以有你的逻辑从获取的书API:

ngOnInit() { 
    if (this.route.snapshot.params && this.route.snapshot.params['id']) { // make sure id is present 
     bookService.getBookById(this.route.snapshot.params[id).subscribe((res)=>{ 
      this.book = res.json(); // this is just an example of where to put your call, not how to make it 
} else { 
//no id received, throw error whatever you need, show blank form etc 
}