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

问题我'm having right now is I'在我的服务中映射我的对象如此 .map(projects => projects.find(project => project.id === id)); 然后我试图在我的竞争对手中运行.subscribe像这样

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

我收到了错误的Typescript说 project does not exist on type 我相信这意味着它没有在我的组件中定义 . 但是我尝试使用observable的所有例子显然都是我自己的代码 .

我仍然试图绕着observables包围我有预感我不应该在我的服务中运行.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 || {};
  }
}