繁体   English   中英

返回类型打字稿函数中的问题

[英]problem in return type typescript function

我的打字稿函数中有一个简单的函数,它返回一个数字:

import { Input } from '@angular/core';
export class UsersService {
  currentusers = [
    {
      name: 'kanzari zied',
      age: 29
    },
    {
      name: 'ahmed mastouri',
      age: 32
    },
    {
      name: 'samir bargaoui',
      age: 40
    }
  ];
  getUserByName(nom: string) :number {     
    this.currentusers.forEach( (item, index) => {
        if(item.name == nom) {
            console.log("its found"+item.age);
            return item.age;
        }
      });
      return 0;
}

}

这是我的组件,它应该显示年龄:

import { Component, OnInit, Input } from '@angular/core';
import { UsersService } from '../services/users.service';
import { ActivatedRoute } from '@angular/router';

@Component({
selector: 'app-single-user',
templateUrl: './single-user.component.html',
styleUrls: ['./single-user.component.scss']
})
export class SingleUserComponent implements OnInit {
@Input() nom:string;
@Input() age:number;
constructor(private UsersService:UsersService,private route: 
ActivatedRoute) { }
ngOnInit() {
this.nom = this.route.snapshot.params['nom'];
console.log("---------"+this.nom);
this.age=this.UsersService.getUserByName(this.nom);   
console.log("current age "+this.age);
  }

  }

问题是:在服务中我可以看到我在 console.log 中的年龄,但是在 component.ts 中它返回 0 !!!! 请我不明白为什么

forEach 没有返回值。 你需要做这样的事情:

  getUserByName(nom: string) :number { 
    const age = 0;    
    this.currentusers.forEach( (item, index) => {
        if(item.name == nom && !age) {
            console.log("its found"+item.age);
            age = item.age;
        }
      });
      return age;
}

您应该使用find方法:

function getUserByName(nom: string): number {
    const user = this.currentusers.find(user => {
        return user.name === nom;
    });
    return user ? user.age : 0;
}

你写的 return 语句,即return item.age; 是forEach的回调函数,不是getUserByName函数。 您需要在getUserByName返回年龄。 此外,在这里find是更合适的方法,因为在 forEach 的情况下,一旦找到值就无法退出。

  getUserByName(nom: string) :number {     
    const result=this.currentusers.find( (item) => {
        return (item.name == nom);
      });
    if(result){
       return result.age
     }
    return 0;
}

Find 是一个很好的方法,它可以更简单地使用:

function getUserByName(nom: string): number {

    const user = this.currentusers.find(a => a.name === nom);
    if(user){
        console.log("its found"+user.age);
     return user.age ;
     }
   return 0;      
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM