gpt4 book ai didi

javascript - Angular 2过早加载组件

转载 作者:行者123 更新时间:2023-12-03 06:55:02 25 4
gpt4 key购买 nike

我有一个 Angular 2,它是按以下方式构建的

app.component - 有多个路由 - 其中一个是 some-data-component,它不是首先显示的默认路由。

某些数据组件 - 有一个列表,您可以在其中选择一个项目 - 当选择它时,我想在数据详细信息组件中显示所选项目。

问题是,数据详细信息组件正在应用程序启动时加载 - 我从它的 html 中收到以下错误

Cannot read property 'students' of undefined

这是有道理的,因为我还没有选择一个项目,所以它应该是未定义的

有没有办法让我构建我的应用程序,这样它就不会构建那些其他组件,除非它们被显示?

这是我的代码:

应用程序组件

import { Component, OnInit } from '@angular/core';
import {Routes, Router, ROUTER_DIRECTIVES} from '@angular/router';

import { Dashboard } from './dashboard/dashboard.component';
import {SomeDataComponent} from './some-data-component/some-data-component';

@Component({
selector: 'my-app',
templateUrl: './app/components/app.component.html'
, directives: [ROUTER_DIRECTIVES]
})
@Routes([
{ path: '/somedata', component: SomeDataComponent},
{ path: '/dashboard', component: Dashboard }
])
export class AppComponent implements OnInit {

mobileView: number = 992;
toggle: boolean = false;

constructor(private router: Router) {
this.attachEvents();
}

ngOnInit() {
this.router.navigate(['/dashboard']);
}
}

一些数据组件

import {SomeDataListView} from '../some-data-list-view/some-data-list-view';
import {DataDetailComponent} from '../data-detail/data-detail.component';

import {SomeService} from '../../services/some_service';

@Component({
selector: 'some-data-component',
providers: [SomeService],
templateUrl: 'app/components/some-data/some-data.html',
directives: [SomeDataListView, DataDetailComponent]
})
export class RoutesComponent {
data;
selectedData;

constructor(private someService: SomeService) {
this.data=[]
}

ngOnInit() {
this.data= this.SomeService.all();
}

selectedRouteChanged(route) {
this.selectedRoute = route;
}
}

一些数据.html

<rd-widget>
<rd-widget-body classes="medium no-padding">
<div>
<img src="{{route.imgSrc}}" />
<label>Neighborhood: {{route.name}}</label>
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th class="text-center">ID</th>
<th>Neighborhood</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let student of route.students" (click)="setSelected(route)">
<td>{{student.id}}</td>
<td>{{student.neighborhood}}</td>
<td>
<span class="{{route.tooltipcls}}">
<i class="fa {{route.icon}}"></i>
</span>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</rd-widget-body>
</rd-widget>

最佳答案

您可以使用 Elvis 运算符:

<tr *ngFor="let student of route?.students" ...

关于javascript - Angular 2过早加载组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37317273/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com