Reputation: 43
import { Injectable } from '@angular/core';
export class Test {
public id: number; public name: string; public fid: number
};
export const TESTS: Test[] = [
{id: 1, name: 'Cat', fid: 1},
{id: 2, name: 'Dog', fid: 1},
{id: 3, name: 'Elephant', fid: 1},
{id: 4, name: 'Bird', fid: 1},
{id: 5, name: 'Duck', fid: 2},
{id: 6, name: 'Snake', fid: 2},
{id: 7, name: 'Rabbit', fid: 2},
{id: 8, name: 'Dolphin', fid: 2},
{id: 9, name: 'Sheep', fid: 3},
{id: 10, name: 'Cow', fid: 3},
{id: 11, name: 'Fish', fid: 3},
{id: 12, name: 'Monkey', fid: 3}];
let testsPromise = Promise.resolve(TESTS);
@Injectable()
export class TestService {
getTests(id) {
let items: Test[] = [];
for(var i = 0; i < TESTS.length; i++) {
if(TESTS[i].fid == id) {
items.push(TESTS[i])
}
}
return items;
}
}
It seems that TESTS is unreachable in funciton getTests(id), but testsPromise is available because i receive all data if do return testsPromise in getTests function. Why?
Upvotes: 0
Views: 110
Reputation: 8053
Is Test
an interface like this?
interface Test {
id: number;
name: string;
fid: number;
}
If so, you must initialize items
array before the loop begins (note the use of let
):
getTests(id: number) {
let items: Test[] = [];
// ...
}
Then, make sure that TESTS
, wherever it is declared, is available within the function:
getTests(id: number) {
console.log(TESTS); // do you see this output?
// ...
}
With the above set, your code worked fine for me.
Bonus: if you want further refinement, you can rewrite your function in one line:
getTests(id: number): Test[] {
return TESTS.filter((oneTest: Test) => oneTest.fid === id);
}
Upvotes: 2