TypeScript抛出错误“类型'数据'上不存在”属性'痕迹痕迹'。“

时间:2017-01-22 18:19:12

标签: angular typescript

我有面包屑组件。它编译成JavaScript时工作正常,并且还呈现所需的结果,但IDE会抛出一个我无法纠正的错误。其内容如下: -

[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截图如下: - enter image description here

请帮助解决问题。我收到此错误后,TSLint不会在浏览器上发出任何警告。

1 个答案:

答案 0 :(得分:2)

angular中你必须&#39;使用[name]表示法来获取值。显然,没有&#39;必须&#39;,因为它可以工作,但要让TypeScript编译器停止抱怨使用:

route.snapshot.data['breadcrumb'];

阅读Custom Preloading Strategy并向下滚动到app/selective-preloading-strategy.ts示例文件