Angular2:使用observables为id param路由提供服务

时间:2016-10-28 00:56:10

标签: angular angular2-routing

我尝试根据angular2教程路由我的应用程序,并修改了将所有数据保存在JSON文件中。经过大量的反复试验后,我已经了解了最后一点,但我无法弄清楚在使用observable时如何设置带有和变量的路径。从我所看到的,所有教程都使用了不可用的promises,因为我用可观察的方式路由了我的原始数据。

我现在遇到的问题是我在我的服务中映射我的对象.map(projects => projects.find(project => project.id === id));,然后我试图在我的竞争对手中运行.subscribe

getProject(this.route.snapshot.params['id']) .subscribe(project => this.project = project);

我在打字稿中得到错误并说project does not exist on type,我相信这意味着它没有在我的组件中定义。但我所看到的所有例子都没有他们的"项目"在组件中定义。他们再次使用承诺,我试图使用可观察量,所以显然有些东西是我自己的代码。

我仍然试图绕着可观察的东西包围我有预感我不应该在我的服务中运行.map但是我不确定我应该做什么改为做。

gallery.component

import { Component, Input, OnInit } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { Location }                 from '@angular/common';

import { Project } from '../project';
import { ProjectService } from '../project.service';

@Component({
  selector: 'gallery',
  templateUrl: './gallery.html',
  styleUrls: ['./gallery.scss'],
  providers: [ProjectService]
})

export class GalleryComponent implements OnInit {

  constructor(
    private projectService: ProjectService,
    private route: ActivatedRoute,
    private location: Location
  ) { }

  ngOnInit() {
    this.projectService
      .getProject(this.route.snapshot.params['id'])
      .subscribe(project => this.project = project);
  }
}

project.service

import { Injectable }     from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable }     from 'rxjs/Observable';

import { Project } from './project';

@Injectable()
export class ProjectService {
  private projectsUrl = 'data/project.json'; // URL to web API

  constructor(private http: Http) { }

  getProjects(): Observable<Project[]> {
    return this.http.get(this.projectsUrl)
      .map(this.extractData)
  }

  getProject(id: string): Observable<Project> {
    return this.getProjects()
      .map(projects => projects.find(project => project.id === id));
  }

  private extractData(res: Response) {
    let body = res.json();
    return body.project || {};
  }
}

0 个答案:

没有答案