【问题标题】:How to fetch one item from a JSON feed with the item ID using Typescript / Angular 2?如何使用 Typescript / Angular 2 从带有项目 ID 的 JSON 提要中获取一个项目?
【发布时间】:2016-04-11 23:47:36
【问题描述】:

我有一个 service.ts 文件,其中包含从 JSON 提要获取数据的以下代码:

@Injectable()
export class HeroService {
  constructor(private http: Http) { }

  private _heroesUrl = '/heroes.json';  

  getHeroes() {
    return this.http.get(this._heroesUrl)
      .map(res => <Hero[]>res.json().data)
      .do(data => console.log(data)) 
      .catch(this.handleError);
  }
  private handleError(error: Response) {
    console.error(error);
    return Observable.throw(error.json().error || 'Server error');
  }

  getHero() {
    //** code to go here
  }
}

还有一个使用服务的组件文件:

export class HeroesComponent implements OnInit {
   heroes: Hero[];
   selectedHero: Hero;
   errorMessage: any;

   constructor(private _router: Router, private _heroService: HeroService) { }

   getHeroes() {
       this._heroService.getHeroes()
       .subscribe(
       heroes => this.heroes = heroes,
       error => this.errorMessage = <any>error);
   }

   getHero() {
     let id = this._routeParams.get('id');

     //** code to go here
   }

}

现在,getHeroes() 可以正常工作,并通过 service.ts 从 heros.json 中获取所有项目。但是,我要做的是使用项目的“id”从 heros.json 中只获取一个项目。我该怎么做呢?我尝试使用 .filter 但这没有用。谢谢

【问题讨论】:

    标签: angular angular2-routing angular2-services


    【解决方案1】:

    你应该使用数据的过滤方法,而不是 Observable:

     getHero(id) {
         return this.http.get(this._heroesUrl)
            .map(res => (<Hero[]>res.json().data).filter(hero => hero.id === id))
            .do(data => console.log(data)) 
            .catch(this.handleError);
     }
    

    【讨论】:

      【解决方案2】:

      我觉得我来得太晚了,但这对我来说很好。

      这是我的 service.ts 中的代码 sn-p

       getProject(id: number) {
             console.log(id);
             return this.getProjects()
                    .then(projects => projects.filter(project => project.id == id)[0])
                    .catch(this.handleError);
            }
      

      这就是从我的 component.ts 中使用它的方式

      ngOnInit() {
          this.sub = this.route.params.subscribe(params => {
            if (params['id'] !== undefined) {
              let id = +params['id'];
              this.projectsvc.getProject(id)
                .then(proj => this.currproject = proj);
            }
      
          });
        }
      

      希望对你有帮助

      【讨论】:

        【解决方案3】:

        一个更好的方法可能如下。

        在 service.ts 中:

        getHero(id: number): Observable<Hero> {
            return this.getHeroes()
                .map((heroes: Hero[]) => heroes.find(hero => hero.id === id));
        }
        

        在 component.ts 中:

        getHero() {
            let id = this._routeParams.get('id');
            this._heroService.getHero(id)
                    .subscribe(
                        hero => this.hero = hero,
                        error => this.errorMessage = <any>error);
        }
        

        【讨论】:

          猜你喜欢
          • 2016-08-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-02-16
          • 1970-01-01
          • 2014-04-08
          • 1970-01-01
          相关资源
          最近更新 更多