[英]Angular4 + Cannot read property 'url' of undefined
在單擊鏈接和更改屏幕上元素的顏色之間的邏輯上進行工作。 在此示例中,我想在單擊鏈接時更改h1標簽的顏色。 到目前為止,這就是我所擁有的。 藍色鏈接無法導航到其他組件
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AppComponent } from './app.component';
import { BlueComponent } from './blue/blue.component';
import { AppRoutingModule } from './app-routing.module';
import { routes } from './app-routing.module';
@NgModule({
declarations: [
AppComponent,
BlueComponent
],
imports: [
BrowserModule,
AppRoutingModule,
RouterModule.forRoot(routes)
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
app.component.ts
import { Component } from '@angular/core';
import { Router, ActivatedRoute, RouterOutlet, Routes } from '@angular/router';
import { BrowserModule } from '@angular/platform-browser';
import { NgClass, CommonModule } from '@angular/common';
@Component({
selector: 'app-root',
styleUrls: ['./app.component.css'],
template: `<h1 [ngClass]="{'red': (router.url === '/'),
'blue': (router.url === '/blue')}">Color Changer</h1>
<a routerLink='/'>Red</a>
<a routerLink='/blue'>Blue</a>
<router-outlet></router-outlet>
`
})
export class AppComponent {
constructor(router: Router) {}
}
app.component.css
.red {
color: red;
}
.blue {
color: blue;
}
APP-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AppComponent } from './app.component';
import { BlueComponent } from './blue/blue.component';
export const routes: Routes = [
{ path: '', component: AppComponent },
{ path: 'blue', component: BlueComponent },
];
@NgModule({
imports: [ RouterModule.forRoot(routes) ],
exports: [ RouterModule ]
})
export class AppRoutingModule {}
我不斷收到此錯誤,阻止我的更改應用,並可能阻止鏈接導航:
錯誤TypeError:無法在checkAndUpdateView(core.es5)處以Object.debugUpdateDirectives的Object.eval [作為updateDirectives](AppComponent.html:1)[作為updateDirectives](core.es5.js:13058)讀取未定義的屬性'url'。調用對象的callViewAction(core.es5.js:12603)處的js:12238),對象的callWithDebugContext(core.es5.js:12244)處的checkAndUpdateView(core.es5.js:12244)處的execComponentViewsAction(core.es5.js:12535)處的Object .debugCheckAndUpdateView [作為checkAndUpdateView](core.es5.js:12998),位於ViewRef_.webpackJsonp ... / .. / .. / core/@angular/core.es5.js.ViewRef_.detectChanges(core.es5.js: 10169),位於core.es5.js:4807
Inspector中的源代碼下划線
<h1 [ngClass]="{'red': (route.url === '/'),
'blue': (route.url === '/blue')}">Color Changer</h1>
那條線怎么了?
您需要使路由器可用於整個組件。
constructor(router: Router){
// router is only available here
}
為此,您可以將變量設為私有
constructor(private router: Router){}
現在路由器可以通過this.router在整個組件中使用
旁注:以上解決方案是以下解決方案的簡寫
export class AppComponent {
private router: Router;
constructor(router: Router) {
this.router = router;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.