“数字”类型的参数不能分配给“字符串”类型的参数

Gur*_*bii 5 parameters angular

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

argument of type 'number' is not assignable to a parameter of type 'string'
Run Code Online (Sandbox Code Playgroud)

就我所能看到的而言,它是一个字符串而不是一个数字,所以我很困惑。

我的代码: 模型

export class Actor {
    lastName: string;
    profession: string;
    bio: string;
    url: string;
    imageUri: string;
    name: string;
    id: string;
    realName: string;
}
Run Code Online (Sandbox Code Playgroud)

服务

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));
    }
}
Run Code Online (Sandbox Code Playgroud)

成分

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

我也收到以下错误

cannot find name 'actor' in the component file
Run Code Online (Sandbox Code Playgroud)

Saj*_*ran 6

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

 this.actorService.getActor(params.get('name'))).subscribe(hero => this.actor = actor);
Run Code Online (Sandbox Code Playgroud)

还在 ts 中声明一个变量为

actor : any;
Run Code Online (Sandbox Code Playgroud)


Ale*_*nov 5

就我所能看到的而言,它是一个字符串而不是一个数字

+params.get('name')是一个数字,因为+JavaScript 中的一元将其操作数转换为数字