I have a Component and a Service:
Component:
export class WebUserProfileViewComponent {_x000D_
persons: Person [];_x000D_
personId: number;_x000D_
constructor( params: RouteParams, private personService: PersonService) {_x000D_
_x000D_
_x000D_
this.personId = params.get('id');_x000D_
this.persons = this. personService.getPersons();_x000D_
console.log(this.personId); _x000D_
}_x000D_
}
_x000D_
Service:
@Injectable()_x000D_
export class PersonService {_x000D_
getPersons(){_x000D_
var persons: Person[] = [_x000D_
{id: 1, firstName:'Hans', lastName:'Mustermann', email: '[email protected]', company:'Test', country:'DE'},_x000D_
{id: 2, firstName:'Muster', lastName:'Mustermann', email: '[email protected]', company:'test', country:'DE'},_x000D_
{id:3, firstName:'Thomas', lastName:'Mustermann', email: '[email protected]', company:'test', country:'DE'}_x000D_
];_x000D_
_x000D_
return persons;_x000D_
}_x000D_
}
_x000D_
I want to get the Person Item with the Id ('personID'). The personID i get from Routeparam. For that I need the foreach loop? But I haven´t found a solution for this.
This question is related to
angular
typescript
angular2-services
from TypeScript you can use native JS array filter() method:
let filteredElements=array.filter(element => element.field == filterValue);
it returns an array with only matching elements from the original array (0, 1 or more)
Reference: https://developer.mozilla.org/it/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
You need to use method Array.filter
:
this.persons = this.personService.getPersons().filter(x => x.id == this.personId)[0];
or Array.find
this.persons = this.personService.getPersons().find(x => x.id == this.personId);
Use this code in your service:
return this.getReports(accessToken)
.then(reports => reports.filter(report => report.id === id)[0]);
Transform the data structure to a map if you frequently use this search
mapPersons: Map<number, Person>;
// prepare the map - call once or when person array change
populateMap() : void {
this.mapPersons = new Map();
for (let o of this.personService.getPersons()) this.mapPersons.set(o.id, o);
}
getPerson(id: number) : Person {
return this.mapPersons.get(id);
}
Try this
let val = this.SurveysList.filter(xi => {
if (xi.id == parseInt(this.apiId ? '0' : this.apiId))
return xi.Description;
})
console.log('Description : ', val );
You could combine .find
with arrow functions and destructuring. Take this example from MDN.
const inventory = [
{name: 'apples', quantity: 2},
{name: 'bananas', quantity: 0},
{name: 'cherries', quantity: 5}
];
const result = inventory.find( ({ name }) => name === 'cherries' );
console.log(result) // { name: 'cherries', quantity: 5 }
Source: Stackoverflow.com