【问题标题】:Angular2 routing - url doesn't change and page doesn't loadAngular2 路由 - url 不会改变并且页面不会加载
【发布时间】:2017-06-01 08:30:27
【问题描述】:

我已经开始使用 typescript 学习 angular2,我正在尝试实现 book/:id 的路线,但我的路线没有改变,html 也没有。

我有一个名为 app.module.ts 的文件,其中包含我所有其他可用的路由:

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

我的 book 组件使用 ngOnInit 从 url 获取 id

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”中输入网址,我会收到此堆栈跟踪错误:

处理请求时发生未处理的异常。 异常:调用节点模块失败并出现错误:TypeError:不能 读取未定义的属性“id” AppView._View_BookComponent0.detectChangesInternal (BookComponent.ngfactory.js:27:82) 在 AppView.detectChanges (C:\Users\GOWDY_N\Documents\Visual Studio 2015\Projects\MyAngular2App\MyAngular2App\node_modules\@angular\core\bundles\core.umd.js:9566:18) 在 AppView.detectViewChildrenChanges (C:\Users\GOWDY_N\Documents\Visual Studio 2015\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 Studio 2015\Projects\MyAngular2App\MyAngular2App\node_modules\@angular\core\bundles\core.umd.js:9566:18) 在 AppView.detectContentChildrenChanges (C:\Users\GOWDY_N\Documents\Visual Studio 2015\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 Studio 2015\Projects\MyAngular2App\MyAngular2App\node_modules\@angular\core\bundles\core.umd.js:9566:18) 在 AppView.detectViewChildrenChanges (C:\Users\GOWDY_N\Documents\Visual Studio 2015\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)

此外,如果我尝试从主屏幕导航到图书页面,我的 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 消息,并且图书馆服务也可以正常工作。

我看不到我错过了什么。

【问题讨论】:

  • 您是否测试过您的代码是否存在该 id 值?首先在 ngOnInit 上执行 console.log(JSON.stringify(this.route.snapshot.params["id"])); 以查看您是否具有价值。
  • @echonax 如果我点击主页上的链接,console.log 在 ngOnInit 中工作,但 url 不会改变。如果我手动输入 url,我会得到一个堆栈跟踪。我将更新我的帖子,以便您可以看到我在说什么。
  • 我知道你的意思,我可以猜到你得到堆栈跟踪的原因,但如果这是我的想法,你应该养成调试代码的习惯。所以请插入console.log。如果代码没有到达 oninit,请在构造函数上尝试。

标签: angular asp.net-core-mvc angular2-routing


【解决方案1】:

您正在尝试直接访问路由器参数,这可能会导致页面加载时未定义。

尝试将其保存到局部变量中,例如:

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

然后执行 params[] 上的代码

【讨论】:

    【解决方案2】:

    我在最初的问题上取得了一些进展。因为我正在学习 angular2 以及我可以用它做的所有事情,所以我最初编写的代码是在用户从主页转到带有 url book/1 的书页时使用 subscribe 的。

    但是我现在改变了我使用订阅的方式,因为我收到了一个模板错误。

    我之前在 ngOnInit 上使用过这个:

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

    但现在我把它改成了这样:

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

    现在使用 subscribe 感觉有点多余,因为它只是一个简单的 api 调用,我不必在我的 Angular 代码中观察任何内容。

    我暂时将这个答案留在这里,但如果有人有更好的答案和解释,我会将他们的答案标记为正确。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-04-07
      • 2019-01-16
      • 2021-10-07
      • 2017-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多