【问题标题】:Angular 2 Routes OptionsAngular 2 路由选项
【发布时间】:2017-05-04 19:07:14
【问题描述】:

我是 Angular 和 Node JS 的新手,我目前正在开发一个应用程序,在决定如何在我的不同组件之间进行最佳导航时,我遇到了一些问题。

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

单击书名后,我希望导航到与该书关联的组件,并专门提取该条目的信息,例如 cmets。

Component that will render specific book information

使用 Angular 2(MEAN 堆栈),我想了解我应该如何解决这样的问题 - 我是否应该存储任何特定值以便更轻松地导航和从数据库中提取有关图书的信息。

<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>

任何建议将不胜感激

【问题讨论】:

  • 我看不到你的截图链接,上面写着503error
  • 谢谢你的邮件,奇怪 - 我已经重新上传了
  • 请尽量不要在同一个问题中同时标记 Angular 和 Angularjs;尽管它们的名称明显令人困惑,但它们是完全不同的框架。

标签: javascript angular routes angular-ui-router


【解决方案1】:

我这样做的方法是在你的路由器链接的末尾添加一个 id,这样它就会路由到 book/thebookid 之类的东西。

然后你会像这样在你的路由模块中添加一些东西:

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

然后在您的图书组件中,您需要在 URL 中查找该 id 并告诉它从您的服务中获取图书。您需要导入一些东西来实现它。

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

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

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

您实际上可能也想从“@angular/core”导入 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
}

【讨论】:

    猜你喜欢
    • 2016-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-28
    相关资源
    最近更新 更多