简体   繁体   English

解决promise angular2:类型“ []”上不存在属性“ includes”

[英]Resolving promise angular2: Property 'includes' does not exist on type '[]'

I am getting error 我遇到错误

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.

the code will not compile and run, this error is on npm start . 该代码将无法编译和运行,此错误在npm start

hero.service.ts: 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; }));
  }
}

hero-detail.component.ts: hero-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");
                }
            }
        );
    }
}

mock-heroes.ts: 模拟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: hero.ts:

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

export class HeroIds {
    id: number;
}

Removing the Promise<Hero[]> part from getHeroIds just causes getHeroIds删除Promise<Hero[]>部分只是导致

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.

Array.prototype.includes() is part of ES2016 specification ( link ). Array.prototype.includes()是ES2016规范的一部分( link )。 You have to include this library in TypeScript's compilation. 您必须将此库包含在TypeScript的编译中。 In your tsconfig.json add 在您的tsconfig.json添加

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

and it should work. 它应该工作。

Nothing to do with your code, promises, or Angular. 与您的代码,promise或Angular无关。 Typescript has the following opinion: 打字稿有以下意见:

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

That property certainly exists on my Array type; 该属性肯定存在于我的 Array类型上; you'll have to investigate why it doesn't on yours. 您将不得不调查为什么它不属于您。

Edit : Ah, Sasxa's answer explains why, and how to fix it. 编辑 :啊, Sasxa的答案说明了原因以及如何解决。

Which browser are you using? 您正在使用哪个浏览器?

Looking at the Can I Use site I see that this method is implemented in few browsers, like Chrome and Opera. 在“我可以使用”网站上,我看到这种方法是在少数浏览器(例如Chrome和Opera)中实现的。

See this: http://caniuse.com/#search=includes 看到这个: http : //caniuse.com/#search=includes

I think is just that you are using a method that your browser does not understant yet. 我认为这只是您使用的浏览器还算不错的一种方法。

For solving your problem, use find instead includes : 为了解决您的问题,请使用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");
            }
        }
    );
}

A lucky hit on Angular 2 how to return array of objects from nested promise shows a guy using '< any >'. Angular 2的幸运命中如何从嵌套的Promise返回对象数组,显示了一个使用'<any>'的家伙。 This solved my problem, code is working again 这解决了我的问题,代码再次正常工作

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在“订阅”类型-angular2中缺少属性“包含” - Property 'includes' is missing in type 'Subscription' -angular2 Angular2和Typescript-类型上不存在属性名称 - Angular2 & Typescript - Property name does not exist on type 类型&#39;any []&#39;(JSON)上不存在Angular2属性 - Angular2 Property does not exist on type 'any[]' (JSON) Angular 2属性订阅在Promise类型上不存在<any> - Angular 2 Property subscribe does not exist on type Promise <any> Angular 管道上的 .includes 返回“属性 &#39;includes&#39; 在类型 &#39;never&#39;.ts(2339)&#39; 上不存在错误消息 - .includes on Angular pipe is returning 'Property 'includes' does not exist on type 'never'.ts(2339)' error message &#39;Promise&#39; 类型不存在属性 &#39;subscribe&#39; - Property 'subscribe' does not exist on type 'Promise' Angular2 map - &gt; subscribe数据类型错误(类型&#39;ErrorObservable&#39;上不存在属性&#39;length&#39;。) - Angular2 map -> subscribe data type error ( Property 'length' does not exist on type 'ErrorObservable'.) “承诺”类型上不存在“订阅” <User> 角6 - Subscribe' does not exist on type 'Promise<User>' Angular 6 使用Ionic2和Angular2的类型&#39;Navigator&#39;上不存在属性&#39;connection&#39; - Property 'connection' does not exist on type 'Navigator' using Ionic2 and Angular2 Angular2打字稿错误TS2339:类型“ Y”上不存在属性“ x” - Angular2 typescript error TS2339: Property 'x' does not exist on type 'Y'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM