Angular2路由-URL不变,页面不加载 [英] Angular2 routing - url doesn't change and page doesn't load

查看:70
本文介绍了Angular2路由-URL不变,页面不加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经开始使用typescript学习angular2,并且正在尝试实现book/:id的路由,但是我的路由没有改变,而html也没有.

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.

我有一个名为app.module.ts的文件,该文件具有我所有其他有效的路由:

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

我的书组件,它使用ngOnInit从URL获取ID

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);
    }
}

如果我在浏览器中输入网址" http://localhost:60369/book/1 我收到此堆栈跟踪错误:

If I type the url in the browser "http://localhost:60369/book/1" I get this stack trace error:

处理请求时发生未处理的异常.异常:调用节点模块失败,并显示以下错误:TypeError:无法在以下位置读取未定义的属性"id"AppView._View_BookComponent0.detectChangesInternal(BookComponent.ngfactory.js:27:82)在AppView.detectChanges(C:\ Users \ GOWDY_N \ Documents \ Visual Studio2015 \ Projects \ MyAngular2App \ MyAngular2App \ node_modules \ @angular \ core \ bundles \ core.umd.js:9566:18)在AppView.detectViewChildrenChanges(C:\ Users \ GOWDY_N \ Documents \ Visual Studio2015 \ Projects \ MyAngular2App \ MyAngular2App \ node_modules \ @angular \ core \ bundles \ core.umd.js:9592:23)在AppView._View_BookComponent_Host0.detectChangesInternal(BookComponent_Host.ngfactory.js:32:8)在AppView.detectChanges(C:\ Users \ GOWDY_N \ Documents \ Visual Studio2015 \ Projects \ MyAngular2App \ MyAngular2App \ node_modules \ @angular \ core \ bundles \ core.umd.js:9566:18)在AppView.detectContentChildrenChanges(C:\ Users \ GOWDY_N \ Documents \ Visual Studio2015 \ Projects \ MyAngular2App \ MyAngular2App \ node_modules \ @angular \ core \ bundles \ core.umd.js:9584:23)在AppView.detectChangesInternal(C:\ Users \ GOWDY_N \ Documents \ Visual工作室2015 \ Projects \ MyAngular2App \ MyAngular2App \ node_modules \ @angular \ core \ bundles \ core.umd.js:9576:18)在AppView.detectChanges(C:\ Users \ GOWDY_N \ Documents \ Visual Studio2015 \ Projects \ MyAngular2App \ MyAngular2App \ node_modules \ @angular \ core \ bundles \ core.umd.js:9566:18)在AppView.detectViewChildrenChanges(C:\ Users \ GOWDY_N \ Documents \ Visual Studio2015 \ Projects \ MyAngular2App \ MyAngular2App \ node_modules \ @angular \ core \ bundles \ core.umd.js:9592:23)在AppView.detectChangesInternal(C:\ Users \ GOWDY_N \ Documents \ Visual工作室2015 \ Projects \ MyAngular2App \ MyAngular2App \ node_modules \ @angular \ core \ bundles \ core.umd.js:9577:18)

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中使用,但网址不会更改,并且不会加载新内容.

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>

点击此链接:

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

没有给我一个堆栈跟踪错误,但是没有加载新内容,并且URL保持不变.在book.component.ts中我还收到一条console.log消息,图书馆服务也可以正常工作.

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.

推荐答案

我最初遇到的问题取得了一些进展.因为我正在学习angular2及其所有功能,所以我最初编写的代码是当用户从主页转到带有url book/1的书页时使用subscribe的代码.

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.

我以前在ngOnInit上使用过它:

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);
        });
    }

使用订阅现在感觉有点多余,因为因为这只是一个简单的api调用,所以我不必在角度代码中观察任何内容.

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.

这篇关于Angular2路由-URL不变,页面不加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆