我真的需要使用管道构造代替`of`吗?

时间:2019-02-28 05:38:05

标签: angular

在下面的getHero()中,我认为我可以用.pipeof(HEROES[id])代替复杂的of(this.heroes[id])方法,但这似乎行不通。没有错误,但没有任何反应。 of()函数在getHeroes()中可以正常工作。有人知道为什么of函数在getHero()中不起作用吗?

hero.service.ts

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

import { Observable, of } from 'rxjs';
import { map } from 'rxjs/operators';

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

@Injectable({
  providedIn: 'root',
})
export class HeroService {

heroes: Hero[];

  constructor(private messageService: MessageService) { }

  getHeroes(): Observable<Hero[]> {
    // TODO: send the message _after_ fetching the heroes
    this.messageService.add('HeroService: fetched heroes');  
    return of(HEROES);
  }

  getHero(id: number | string) {
    return this.getHeroes().pipe(
      // (+) before `id` turns the string into a number
      map((heroes: Hero[]) => heroes.find(hero => hero.id === +id))
    );
//Note: using `return of(HEROES[+id])` or `return of(this.heroes[id])` in place of 
//this.getHeroes.pipe . . .  doesn't work. Anyone know why not?
  }
}

mock-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;
}

hero-detail.component.html:

<h2>HEROES</h2>
<div *ngIf="hero$ | async as hero">
  <h3>"{{ hero.name }}"</h3>
  <div>
    <label>Id: </label>{{ hero.id }}</div>
  <div>
    <label>Name: </label>
    <input [(ngModel)]="hero.name" placeholder="name"/>
  </div>
  <p>
    <button (click)="gotoHeroes(hero)">Back</button>
  </p>
</div>

1 个答案:

答案 0 :(得分:1)

let id="0", 
HEROES[+id], return {id:11,name:'Mr.Nice'}

let id="11"
HEROES[+id] //give error because don't exist HEROES[11] 

let id="11"
HEROES.find(hero=>hero.id==+id), return {id:11,name:'Mr.Nice'}

您当然可以使用of(HEROES [+ id]),但是需要记住,您需要发送数组的“索引”,而不是“ id”的值。