2017-01-17 10 views
0

typescriptでangular2を学習し始めましたが、book /:idのルートを実装しようとしていますが、ルートは変更されず、どちらもない。Angular2ルーティング - URLは変更されず、ページはロードされません

私はすべての私の他のルートを持っているapp.module.tsと呼ばれるこのファイルを持っている作品:

app.module.ts IDを取得するためにngOnInitを使用しています

import { NgModule } from '@angular/core'; 
import { RouterModule } from '@angular/router'; 
import { UniversalModule } from 'angular2-universal'; 
import { AppComponent } from './components/app/app.component' 
import { NavMenuComponent } from './components/navmenu/navmenu.component'; 
import { HomeComponent } from './components/home/home.component'; 
import { FetchDataComponent } from './components/fetchdata/fetchdata.component'; 
import { CounterComponent } from './components/counter/counter.component'; 
import { BookComponent } from'./components/book/book.component'; 

@NgModule({ 
    bootstrap: [ AppComponent ], 
    declarations: [ 
     AppComponent, 
     NavMenuComponent, 
     CounterComponent, 
     FetchDataComponent, 
     HomeComponent, 
     BookComponent 
    ], 
    imports: [ 
     UniversalModule, // Must be first import. This automatically imports BrowserModule, HttpModule, and JsonpModule too. 
     RouterModule.forRoot([ 
      { path: '', redirectTo: 'home', pathMatch: 'full' }, 
      { path: 'home', component: HomeComponent }, 
      { path: 'book/:id', component: BookComponent }, 
      { path: 'counter', component: CounterComponent }, 
      { path: 'fetch-data', component: FetchDataComponent }, 
      { path: '**', redirectTo: 'home' } 
     ]) 
    ] 
}) 
export class AppModule { 
} 

マイブックコンポーネントURLから

book.component.ts

import { Component } from '@angular/core'; 
import { LibraryService } from '../../services/app.service.library'; 
import { ActivatedRoute } from '@angular/router'; 

@Component({ 
    selector: 'book', 
    template: require('./book.component.html'), 
    providers: [LibraryService] 
}) 
export class BookComponent { 
    book: any; 

    constructor(private libraryService: LibraryService, private route: ActivatedRoute) {} 

    ngOnInit() { 
     // prints to console id e.g. 1 
     console.log(this.route.snapshot.params["id"]); 
     this.libraryService.getBook(this.route.snapshot.params["id"]) 
      .subscribe(response => this.book = response); 
    } 
} 

私は、ブラウザで「http://localhost:60369/book/1を」URLを入力した場合、私はこのスタックトレースのエラーを取得:

An unhandled exception occurred while processing the request. Exception: Call to Node module failed with error: TypeError: Cannot read property 'id' of undefined at AppView._View_BookComponent0.detectChangesInternal (BookComponent.ngfactory.js:27:82) at AppView.detectChanges (C:\Users\GOWDY_N\Documents\Visual Studio 2015\Projects\MyAngular2App\MyAngular2App\node_modules\@angular\core\bundles\core.umd.js:9566:18) at AppView.detectViewChildrenChanges (C:\Users\GOWDY_N\Documents\Visual Studio 2015\Projects\MyAngular2App\MyAngular2App\node_modules\@angular\core\bundles\core.umd.js:9592:23) at AppView._View_BookComponent_Host0.detectChangesInternal (BookComponent_Host.ngfactory.js:32:8) at AppView.detectChanges (C:\Users\GOWDY_N\Documents\Visual Studio 2015\Projects\MyAngular2App\MyAngular2App\node_modules\@angular\core\bundles\core.umd.js:9566:18) at AppView.detectContentChildrenChanges (C:\Users\GOWDY_N\Documents\Visual Studio 2015\Projects\MyAngular2App\MyAngular2App\node_modules\@angular\core\bundles\core.umd.js:9584:23) at AppView.detectChangesInternal (C:\Users\GOWDY_N\Documents\Visual Studio 2015\Projects\MyAngular2App\MyAngular2App\node_modules\@angular\core\bundles\core.umd.js:9576:18) at AppView.detectChanges (C:\Users\GOWDY_N\Documents\Visual Studio 2015\Projects\MyAngular2App\MyAngular2App\node_modules\@angular\core\bundles\core.umd.js:9566:18) at AppView.detectViewChildrenChanges (C:\Users\GOWDY_N\Documents\Visual Studio 2015\Projects\MyAngular2App\MyAngular2App\node_modules\@angular\core\bundles\core.umd.js:9592:23) at AppView.detectChangesInternal (C:\Users\GOWDY_N\Documents\Visual Studio 2015\Projects\MyAngular2App\MyAngular2App\node_modules\@angular\core\bundles\core.umd.js:9577:18)

また、私は、ホーム画面から本のページに移動しようとした場合、私にconsole.logはngOnInitで動作しますURLは変更されず、新しいコンテンツは読み込まれません。このリンク上の

home.component.ts

import { Component } from '@angular/core'; 
import { LibraryService } from '../../services/app.service.library'; 

@Component({ 
    selector: 'home', 
    template: require('./home.component.html'), 
    providers: [LibraryService] 
}) 
export class HomeComponent { 
    books: Array<any>; 

    constructor(private libraryService: LibraryService) { } 

    ngOnInit() { 
     this.libraryService.getBooks().subscribe(response => { 
      this.books = response; 
     }); 
    } 
} 

home.component.html

<div class="row"> 
<div class="jumbotron"> 
    <h1>Book Store</h1> 

    <div id="custom-search-input"> 
     <div class="input-group col-md-12"> 
      <input type="text" class="form-control input-lg" placeholder="Book title, author, etc" /> 
      <span class="input-group-btn"> 
       <button class="btn btn-info btn-lg" type="button"> 
        <i class="glyphicon glyphicon-search"></i> 
       </button> 
      </span> 
     </div> 
    </div> 

</div> 
<div class="col-md-12"> 
    <ul> 
     <li *ngFor="let book of books" style="list-style-type: none; padding: 10px;" class="col-md-4 hvr-curl-top-left"> 
      <div class="card" style="border-color: black; border-style: solid; border-width: thin; padding: 5px;"> 
       <div class="card-block"> 
        <h3 class="card-title">{{book.title}}</h3> 
        <p class="card-text">{{book.description}}</p> 
        <a href="#" [routerLinkActive]="['link-active']" class="btn btn-primary" [routerLink]="['/book', book.id]">More details</a> 
       </div> 
      </div> 
     </li> 
    </ul> 
</div> 

クリック:

<a href="#" [routerLinkActive]="['link-active']" class="btn btn-primary" [routerLink]="['/book', book.id]">More details</a> 

私にスタックトレースエラーは表示されませんが、新しいコンテンツは読み込まれず、URLは同じままです。また、book.component.ts内にconsole.logメッセージがあり、ライブラリサービスも同様に動作します。

私には何が欠けているのか分かりません。

+1

id値が存在するかどうかでコードをテストしましたか?あなたが値を持っているかどうかを見るために、 'console.log(JSON.stringify(this.route.snapshot.params [" id "]));をngOnInitの最初のものとして行います。 – echonax

+0

@echonaxホームページからリンクをクリックすると、console.logはngOnInitで動作しますが、URLは変更されません。手動でURLを入力すると、スタックトレースが取得されます。私は自分の投稿を更新して、私が話していることを見ることができます。 –

+0

私はあなたが何を意味しているのか知っているので、スタックトレースを取得している理由を推測できますが、それが私の考えであれば、コードをデバッグする習慣が必要です。ですから、console.logを挿入してください。コードがoninitに到達していない場合は、コンストラクタでそれを試してください。 – echonax

答えて

0

ルータのパラメータに直接アクセスしようとしています。これは、ページの読み込み時に未定義の原因となる可能性があります。私は私の最初の問題でいくつかの進歩を遂げて

1

[]のparams上のコードを実行した後

let params: Params = this.route.snapshot.params; 

は次のようにローカル変数に保存してください。私がangular2とそれを使ってできることすべてを学んでいるので、ユーザーがホームページからurl book/1などのブックページに行くときに購読するコードを書きました。

しかし、テンプレートエラーが発生したため、私がsubscribeを使用している方法を変更しました。

ngOnInit() { 
    this.libraryService.getBooks().subscribe(response => { 
     this.books = response; 
    }); 
} 

しかし、今、私はこれにそれを変更しました:私はngOnInitに前にこれを使用していた

ので、それは単純なAPIだから

ngOnInit() { 
     this.sub = this.route.params.subscribe(params => { 
      const id = params["id"]; 
      this.book = this.libraryService.getBook(id); 
     }); 
    } 

今購読使い方は少し冗長に感じていますコール、私は角のコードで何も観察する必要はありません。

私はここでこの回答を残しておきますが、誰かが説明でより良い回答を得た場合は、正しい答えとしてマークします。

関連する問題