Reputation: 6531
I've started learning angular2 with typescript and I'm trying to implement a route of book/:id but my route doesn't change and the html doesn't neither.
I have this file called app.module.ts which has all my other routes which work:
app.module.ts
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 {
}
My book component which uses ngOnInit to get id from 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);
}
}
If I type the url in the browser "http://localhost:60369/book/1" I get this stack trace error:
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)
Also if I try to navigate to the book page from the home screen, my console.log works in ngOnInit but the url doesn't change and the new content doesn't load.
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>
Clicking on this link:
<a href="#" [routerLinkActive]="['link-active']" class="btn btn-primary" [routerLink]="['/book', book.id]">More details</a>
Doesn't give me a stack trace error but the new content doesn't load and the url stays the same. I also get a console.log message within book.component.ts and library service works as well.
I can't see what I'm missing.
Upvotes: 0
Views: 1996
Reputation: 6531
I made some progress with my initial problem. Because I'm learning angular2 and everything that I can do with it, I originally wrote the code to use subscribe when the user goes from the home page to the book page with url book/1 for example.
However I've now changed the way I'm using subscribe because I was getting a template error.
I was using this before on ngOnInit:
ngOnInit() {
this.libraryService.getBooks().subscribe(response => {
this.books = response;
});
}
But now I've changed it to this:
ngOnInit() {
this.sub = this.route.params.subscribe(params => {
const id = params["id"];
this.book = this.libraryService.getBook(id);
});
}
Using subscribe now feels a bit redundant because because it's just a simple api call, I don't have to observe anything in my angular code.
I'll leave this answer here for now but if anyone has a better answer with an explanation I'll mark their answer as correct.
Upvotes: 1
Reputation: 490
you are trying to directly access the router params, this might causing the undefined as the page loads.
Try saving it to a local variable like:
let params: Params = this.route.snapshot.params;
After that execute the code on params[]
Upvotes: 0