TypeScript引发错误“属性'面包屑'在类型'数据'上不存在。”
问题描述:
我有一个Breadcrumb组件。它在编译为JavaScript时也可以正常工作,并且可以呈现所需的结果,但IDE会抛出一个我无法纠正的错误。它说如下: -TypeScript引发错误“属性'面包屑'在类型'数据'上不存在。”
[ts] Property 'breadcrumb' does not exist on type 'Data'.
我的面包屑的代码如下: -
import { Component } from '@angular/core';
import { Router, ActivatedRoute, NavigationEnd } from '@angular/router';
import 'rxjs/add/operator/filter';
import { BreadcrumbModel } from './breadcrumb.model';
@Component({
selector: 'breadcrumb',
template: `
<ol class="breadcrumb">
<li *ngFor="let breadcrumb of breadcrumbs; let last = last">
<a [routerLink]="breadcrumb.url">{{breadcrumb.label}}</a>
</li>
</ol>`
})
export class BreadcrumbComponent {
breadcrumbs: Array<BreadcrumbModel>;
constructor(private router: Router, private route: ActivatedRoute) { }
ngOnInit() {
this.router.events
.filter(event => event instanceof NavigationEnd)
.subscribe(event => { // note, we don't use event
this.breadcrumbs = [];
let currentRoute = this.route.root,
url = '';
do {
let childrenRoutes = currentRoute.children;
currentRoute = null;
childrenRoutes.forEach(route => {
if (route.outlet === 'primary') {
let routeSnapshot = route.snapshot;
url += '/' + routeSnapshot.url.map(segment => segment.path).join('/');
this.breadcrumbs.push({
label: route.snapshot.data.breadcrumb,
url: url
});
currentRoute = route;
}
})
} while (currentRoute);
})
}
}
面包屑模型的代码如下: -
export class BreadcrumbModel{
label:string;
url:string;
}
错误我进入浏览器如下: -
[at-loader] src\app\shared\core\breadcrumb\breadcrumb.component.ts:34:44
Property 'breadcrumb' does not exist on type '{ [name: string]: any; }'.
errors @ client?cd17:80
sock.onmessage @ socket.js?e5d0:37
EventTarget.dispatchEvent @ eventtarget.js?3e89:51
(anonymous) @ main.js?45b8:274
SockJS._transportMessage @ main.js?45b8:272
EventEmitter.emit @ emitter.js?927b:50
WebSocketTransport.ws.onmessage @ websocket.js?c17e:35
wrapFn @ zone.js?fad3:1039
ZoneDelegate.invokeTask @ zone.js?fad3:275
Zone.runTask @ zone.js?fad3:151
ZoneTask.invoke @ zone.js?fad3:345
我不想将目标从ES5更改为ES6。这似乎不是可行的解决方案。 IDE屏幕截图如下: -
请帮忙解决问题。出现此错误后,TSLint不会在浏览器上发出任何警告。
答
在angular
您必须使用[name]
表示法来获取该值。很显然,没有“必须”,因为它仍然可以正常工作,但要获得打字稿编译器停止抱怨使用:
route.snapshot.data['breadcrumb'];
阅读Custom Preloading Strategy和向下滚动到app/selective-preloading-strategy.ts
样本文件
感谢指出这一点。我试了一下,它的工作原理。 –