1

我的 api 使用数字而不是字符串 id。如果我想这样做,我会收到错误:无法将类型字符串分配给类型编号。该param函数是否仅将字符串作为 id 或如何将其更改为数字?

这是我的代码:

用户服务.ts

// get a user's profile
  getUserDetails(id: number): Observable<any> {
    return this.http.get(`${this.url}/users/${id}/`); 
  }

user.page.html

 <ion-avatar  class="user-image"  slot="start" [routerLink]="['/', 'friendsdet', 'id']">
        <ion-img src="assets/9.jpeg"> </ion-img>
 </ion-avatar>

Friendsdet.page.ts

information: null;
id: number;
...
  ngOnInit() {
     // Get the ID that was passed with the URL
     this.activatedRoute.paramMap.subscribe(params => { 
      this.id = params.get('id'); 
  });


     // Get the information from the API
     this.userService.getUserDetails(this.id).subscribe(result => {
       this.information = result;
       console.log(result);
     });
   }

应用程序路由.module.ts

...

     { path: 'friendsdet/:id', 
      loadChildren: './external-user/friendsdet/friendsdet.module#FriendsdetPageModule'
      },
    ...
4

2 回答 2

2

来自 url 的值将始终是字符串。验证并将它们转换为所需的内容是您的代码的工作。在您的情况下,您可以使用该parseInt()函数获取一个字符串并将其更改为一个数字。

您还应该验证输入是否真的是一个数字,可能使用正则表达式或Number.isInteger函数。

  ngOnInit() {
     // Get the ID that was passed with the URL
     this.activatedRoute.paramMap.subscribe(params => { 
      this.id = validateId(params.get('id')); 
  });

function validateId(id: any) : number {
    if(!Number.isNumeric(id)){
       console.error('number is not a number');
    }
    return parseInt(id);
}
于 2019-11-08T15:17:33.130 回答
-2

让我们试试id: any; 而不是id: number;

于 2019-11-08T15:13:36.777 回答