开发者问题收集

函数不返回任何内容

2017-01-04
109
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;
 }
}

似乎在 getTests(id) 函数中无法访问 TESTS, 但 testsPromise 可用,因为如果在 getTests 函数中返回 testsPromise,我会收到所有数据。为什么?

2个回答

您需要初始化项目:

  var items: Test[] = [];
Eran Shabi
2017-01-04

Test 是一个这样的接口吗?

interface Test {
    id: number;
    name: string;
    fid: number;
}

如果是这样,您必须在循环开始之前初始化 items 数组(请注意 let 的使用):

getTests(id: number) {
    let items: Test[] = [];
    // ...
}

然后,确保 TESTS (无论在何处声明)在函数内均可用:

getTests(id: number) {
    console.log(TESTS); // do you see this output?
    // ...
}

使用上述设置,您的代码对我来说 很好


额外福利:如果您想要进一步完善,您可以用一行重写您的函数:

getTests(id: number): Test[] {
    return TESTS.filter((oneTest: Test) => oneTest.fid === id);
}
rodrigocfd
2017-01-04