i have a simple fonction in my typescript fonction which returns a number:
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;
}
}
and here is my component which should show the age :
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);
}
}
Problem is : in the service i can see the age when i console.log it , but in the component.ts it returns 0 !!!! please i dont understand why
forEach doesn't have a return value. You need to do something like this:
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;
}
You should be using find method:
function getUserByName(nom: string): number {
const user = this.currentusers.find(user => {
return user.name === nom;
});
return user ? user.age : 0;
}
The return statement you wrote ie return item.age;
is for the callback function of forEach, not for the getUserByName
function. You need to return the age in getUserByName
. Also, find
is more suitable method here as in case of forEach, you cannot exit once value is found.
getUserByName(nom: string) :number {
const result=this.currentusers.find( (item) => {
return (item.name == nom);
});
if(result){
return result.age
}
return 0;
}
Find is a good method, and it can be used simpler:
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.