Angular2:+ params ['id']没有将id:string转换为id:number

时间:2016-10-27 22:28:22

标签: angular angular2-routing

您好我正在尝试根据gallery/:id设置Angular2路线。我正在使用教程/阅读angulars网站上的路线文档,并以我现在的代码结束。我面临的问题是我的对象id被定义为一个字符串,在角度解决方案中,它被定义为一个数字。

我仍然希望将id保存为字符串的原因之一是因为我希望URL显示当前图库的标题,其次我想使用id来引用包含特定于路径的信息的JSON文件。这是一种不好的做法吗?

我对当前代码的问题在于:

 ngOnInit(): void {
    this.route.params.forEach((params: Params) => {
      let id = +params['id']; // (+) converts string 'id' to a number
      this.projectService.getProject(id)
        .then(project => this.project = project);
    });
 }

我在打字稿中遇到错误Argument type 'number' is not assignable to parameter type of 'string'

我相信这意味着两件事之一,首先是id没有被转换为数字并且它导致错误或者id被转换为数字但是因为我的类将它定义为字符串它正在标记错误。

有没有解决方法,所以我可以使用路由参数作为字符串?

gallery.component

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

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

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

export class GalleryComponent implements OnInit {
  constructor(
    private projectService: ProjectService,
    private route: ActivatedRoute,
    private location: Location
  ) { }

  ngOnInit(): void {
    this.route.params.forEach((params: Params) => {
      let id = params['id'];
      this.projectService.getProject(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)
      .catch(this.handleError);
  }

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

  private handleError(error: Response | any) {
    // In a real world app, we might use a remote logging infrastructure
    let errMsg: string;
    if (error instanceof Response) {
      const body = error.json() || '';
      const err = body.error || JSON.stringify(body);
      errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
    } else {
      errMsg = error.message ? error.message : error.toString();
    }
    console.error(errMsg);
    return Observable.throw(errMsg);
  }
}

0 个答案:

没有答案