类型为'number'的参数不能赋值给'string'类型的参数

时间:2017-10-04 07:56:53

标签: angular parameters

我对打字稿很新,所以如果这是一个菜鸟问题请原谅我。 我正在使用angular cli制作一个简单的主细节应用程序。但是我收到了这个错误

argument of type 'number' is not assignable to a parameter of type 'string'

到目前为止,我可以看到它是一个字符串,而不是一个数字,所以我很困惑。

我的代码: 模型

export class Actor {
    lastName: string;
    profession: string;
    bio: string;
    url: string;
    imageUri: string;
    name: string;
    id: string;
    realName: string;
}

服务

import { Injectable } from '@angular/core';
import { Actor } from '../model/actor';
// import { ACTORS } from './mock-actors';
import { Http } from '@angular/http';
import 'rxjs/add/operator/toPromise';

@Injectable()
export class ActorService {
    private actorsUrl = '/app/persons.json';
    constructor(private http: Http) { }
    getActors(): Promise<Actor[]> {
        return this.http.get(this.actorsUrl)
            .toPromise().then(response => <Actor[]>response.json().personList)
            /*.toPromise().then(response => response.json().personList as Actor[])*/
            .catch(this.handleError);
    }

    private handleError(error: any): Promise<any> {
        console.error('Error: ', error);
        return Promise.reject(error.message);
    }
    getActor(name: string): Promise<Actor> {
        return this.getActors().then(actors => actors.find(actor => actor.name === name));
    }
}

成分<​​/ P>

import { Component, OnInit } from '@angular/core';
import { Actor } from '../../model/actor';
import { ActivatedRoute, ParamMap } from '@angular/router';
import { Location } from '@angular/common';
import { ActorService } from '../../service/actor.service';
import 'rxjs/add/operator/switchMap';

@Component({
    /*selector: 'actor-detail',*/
    templateUrl: './detail-index.component.html'
})
export class ActorDetailComponent implements OnInit{
    actor: Actor;
    constructor(
        private actorService: ActorService,
        private route: ActivatedRoute,
        private location: Location
    ) {}
    ngOnInit(): void {
        this.route.paramMap.switchMap((params: ParamMap) =>
        this.actorService.getActor(+params.get('name'))) // argument of type 'number' is not assignable to a parameter of type 'string'
            .subscribe(hero => this.actor = actor);
    }
    goBack(): void {
        this.location.back();
    }
}

我也收到以下错误

cannot find name 'actor' in the component file

2 个答案:

答案 0 :(得分:3)

您的方法需要 string 作为参数,将其更改为

 this.actorService.getActor(params.get('name'))).subscribe(hero => this.actor = actor);

也将ts中的变量声明为

actor : any;

答案 1 :(得分:3)

  

目前我可以看到它是一个字符串,而不是一个数字

+params.get('name')是一个数字,因为JavaScript converts its operand to a number中的一元+