2016-11-09 98 views
1

我目前正在閱讀名爲「英雄之旅」的教程,並且我有一個不清楚的部分。Angular2 =>運營商

我有服務:

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

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

@Injectable() 
export class HeroService { 
    getHeroes(): Promise<Hero[]> { 
     return Promise.resolve(HEROES); 
    } 

    getHeroesSlowly(): Promise<Hero[]> { 
     return new Promise<Hero[]>(resolve => 
     setTimeout(resolve, 2000)) // delay 2 seconds 
     .then(() => this.getHeroes()); 
    } 

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

} 

而接下來的模擬:

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' } 
]; 

一切運行良好,但具體的部分是對我來說有點不清楚,如果有人將是巨大的可以澄清我。

其中我談論的部分是:

return this.getHeroes() 
       .then(heroes => heroes.find(hero => hero.id === id)); 
從服務

我明白,第一個被稱爲getHeroes()方法返回從模擬列表,但在那之後會發生什麼? :)

長話短說,什麼是處理heroes => heroes.find(hero => hero.id === id)

謝謝您的快速評論!

現在我明白了什麼是處理「=>」,但我還是不明白的是從那裏英雄對象出現在 heroes => heroes.find(hero => hero.id === id)

+1

見https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Promise和https://developer.mozilla.org/en/docs/Web/ JavaScript的/參考/函數/ Arrow_functions – 2016-11-09 14:28:08

+0

我明白,不知何故就像在Java8中,但哪裏聲明的查找方法和英雄對象出現在哪裏? – Aditzu

+0

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/find – yurzui

回答

1
return this.getHeroes() 
    .then(function(heroes){ 
      heroes.find(function(hero){ 
         hero.id === id} 
    )); 

它需要英雄=英雄,適用.find()方法。

find()方法返回數組中第一個滿足提供的測試函數的元素的值。否則返回undefined。

你也可以使用:

return this.getHeroes() 
     .then(function(heroes){ 
       heroes.find(function(doesNotMatter){ 
          doesNotMatter.id === id} 
     )); 

,仍然可以得到相同的結果與第一個。

假設getHero(ID:號)的ID是12

在第一次運行

doesNotMatter = { id: 11, name: 'Mr. Nice' }; 
doesNotMatter.id = 11 

不能滿足未來

二號.find()運行

doesNotMatter = { id: 12, name: 'Narco' }; 
doesNotMatter.id = 12 

它滿足.find()它停止一個nd返回值。

檢查https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/find

+0

非常有用!謝謝!我認爲查找方法解析列表和英雄是當前元素,但我不知道。 Multumesc mult inca o數據:) – Aditzu