解决承诺angular2:类型'[]'上不存在属性'包含'

时间:2017-03-17 20:12:42

标签: javascript angular angular2-services

我收到错误

app/hero-detail.component.ts(44,29): error TS2339: Property 'includes' does not exist on type '[]'.
app/hero.service.ts(25,25): error TS1122: A tuple type element list cannot be empty.

代码无法编译和运行,此错误在npm start上。

hero.service.ts:

import { Injectable } from '@angular/core';

import { Hero, HeroIds } from './hero';
import { HEROES } from './mock-heroes';

@Injectable()
export class HeroService {

  getHeroes(): Promise<Hero[]> {
    return Promise.resolve(HEROES);
  }

  getHero(id: number): Promise<Hero> {
    return this.getHeroes()
        .then(heroes => heroes.find(hero => hero.id === id));
  }

  getHeroesSlowly(): Promise<Hero[]> {
    return new Promise(resolve => {
      // Simulate server latency with 2 second delay
      setTimeout(() => resolve(this.getHeroes()), 2000);
    });
  }

  getHeroIds(): Promise<[]> {
    return this.getHeroes()
    .then(heroes => heroes.map(function(item) { return item.id; }));
  }
}

英雄detail.component.ts:

import { Component, Input, OnInit } from '@angular/core';
import { ActivatedRoute, Params, Router } from '@angular/router';
import { Location } from '@angular/common';

import 'rxjs/add/operator/switchMap';
import { FlashMessagesService } from 'angular2-flash-messages';

import { Hero, HeroIds }         from './hero';
import { HeroService } from './hero.service';


@Component({
  moduleId: module.id,
  selector: 'my-hero-detail',
  templateUrl: './static/templates/hero-detail.component.html',
  styleUrls: ['./static/css/hero-detail.component.css'],
})
export class HeroDetailComponent implements OnInit {
    @Input() hero: Hero;
    hero_ids: Array<HeroIds> = [];

    constructor(
        private heroService: HeroService,
        private route: ActivatedRoute,
        private location: Location,
        private router: Router,
        private _flashMessagesService: FlashMessagesService
    ) { }

    ngOnInit(): void {
        this.route.params
            .switchMap((params: Params) => this.heroService.getHero(+params['id']))
            .subscribe(hero => this.hero = hero);
    }

    goBack(): void {
        this.location.back();
    }

    gotoDetail(hero_id: string): void {
        this.heroService.getHeroIds()
        .then(
            result => {
                if ( result.includes(+hero_id) ) {
                    this.router.navigate(['/detail', hero_id]);
                } else {
                    this._flashMessagesService.show("Please pick a valid hero ID");
                }
            }
        );
    }
}

模拟heroes.ts:

import { Hero } from './hero';

export const HEROES: Hero[] = [
  {id: 11, name: 'Mr. Nice'},
  {id: 12, name: 'Narco'},
  {id: 13, name: 'Bombasto'},
  {id: 14, name: 'Celeritas'},
  {id: 15, name: 'Magneta'},
  {id: 16, name: 'RubberMan'},
  {id: 17, name: 'Dynama'},
  {id: 18, name: 'Dr IQ'},
  {id: 19, name: 'Magma'},
  {id: 20, name: 'Tornado'}
];

hero.ts:

export class Hero {
  id: number;
  name: string;
}

export class HeroIds {
    id: number;
}

Promise<Hero[]>中移除getHeroIds部分只会导致

app/hero.service.ts(19,5): error TS1131: Property or signature expected.
app/hero.service.ts(23,3): error TS1128: Declaration or statement expected.
app/hero.service.ts(25,15): error TS1005: ';' expected.
app/hero.service.ts(26,12): error TS1005: ':' expected.
app/hero.service.ts(27,68): error TS1005: ',' expected.
app/hero.service.ts(29,1): error TS1128: Declaration or statement expected.

4 个答案:

答案 0 :(得分:9)

Array.prototype.includes()是ES2016规范(http://caniuse.com/#search=includes)的一部分。您必须在TypeScript的编译中包含此库。在tsconfig.json添加

"compilerOptions": {
  "lib": [ "es2016" ]
}

它应该有用。

答案 1 :(得分:1)

与您的代码,承诺或Angular无关。打字稿有以下意见:

app/hero-detail.component.ts(44,29): error TS2339: Property 'includes' 
does not exist on type '[]'.

该属性肯定存在于我的数组类型中;你必须调查它为什么不在你身上。

修改: 啊,Sasxa's answer解释了原因,以及如何解决它。

答案 2 :(得分:1)

您使用的是哪种浏览器?

查看我可以使用的网站,我发现此方法是在少数浏览器中实现的,例如Chrome和Opera。

请参阅:video tutorial

我认为只是您使用的是浏览器尚未理解的方法。

要解决您的问题,请使用find代替includes

gotoDetail(hero_id: string): void {
    this.heroService.getHeroIds()
    .then(
        result => {
            if ( result.find(+hero_id) ) {
                this.router.navigate(['/detail', hero_id]);
            } else {
                this._flashMessagesService.show("Please pick a valid hero ID");
            }
        }
    );
}

答案 3 :(得分:-1)

Angular 2 how to return array of objects from nested promise上的一个幸运点击显示一个人使用'&lt;任何&gt;'。这解决了我的问题,代码再次运行

 getHeroIds(): Promise<any> {
    return this.getHeroes()
    .then(heroes => heroes.map(function(item) { return item.id; }));
  }
}