Angular2 =>运营商
我目前正在阅读名为“英雄之旅”的教程,并且我有一个不清楚的部分。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)
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
非常有用!谢谢!我认为查找方法解析列表和英雄是当前元素,但我不知道。 Multumesc mult inca o数据:) – Aditzu
见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
我明白,不知何故就像在Java8中,但哪里声明的查找方法和英雄对象出现在哪里? – Aditzu
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/find – yurzui