首页 > 解决方案 > 字符串类型的参数不可分配给 paramMap

问题描述

我试图在离子框架中创建一些基本功能。

我已在 model.ts 中将 ID 声明为一个数字,并创建了一个函数来使用 paramMap 访问该值,它显示字符串不可分配给数字的错误。

我正在使用离子 4.0。

ngOnInit() {
    this.route.paramMap.subscribe(paramMap => {
      if (!paramMap.has('placeId')) {
        this.navCtrl.navigateBack('/places/tabs/discover');
        return;
      }
       this.place = this.placesService.getplace(paramMap.get('placeId'));
    });
  }

service.ts是我写getplace函数的地方:

getplace(id: number) {
    return {...this._places.find(
      p => p.id === id
    )};
  }

模型:

import { Time } from '@angular/common';
export class place {
    constructor(
        public id: number,
        public user_id: number,
        public title: string,
        public cooked_time: Date,
        public dispose_time: Date,
        public food_type: string,
        public description: string,
        public serve_quantity: number,
        public imageUrl: string,
        public lat: number,
        public long: number
    ) {}
}

我期望传递一个数字,并且该函数将其作为字符串。

标签: angularionic-frameworkionic4

解决方案


在您的呼叫中使用“+”

this.placesService.getplace(+paramMap.get('placeId')) 

将字符串转换为数字

ngOnInit() {
    this.route.paramMap.subscribe(paramMap => {
      if (!paramMap.has('placeId')) {
        this.navCtrl.navigateBack('/places/tabs/discover');
        return;
      }
       this.place = this.placesService.getplace(+paramMap.get('placeId'));
    });
  }

推荐阅读