首页 文章

Angular 2:从Firebase返回的数据未映射到我的对象数组上

提问于
浏览
0

我使用Observables从Angular 2获取Firebase数据,但是,即使我从http调用得到结果,我也无法在我的实体上映射返回的对象 .

我想映射到食谱阵列 . 食谱是:

export class Recipe {
    constructor(public name: string,
        public description: string,
        public imagePath: string,
        public ingredients: Ingredient[]) {
    }
}

包含Recipes数组的组件类以及对负责获取数据和订阅者的服务的第一次调用是:

export class RecipeListComponent implements OnInit {
  recipes: Recipe[] = [];

  constructor(private recipeService: RecipeService) { }

  ngOnInit() {
    this.recipes = this.recipeService.getRecipes();
    this.recipeService.recipesChanged.subscribe(
      (recipes: Recipe[]) => this.recipes = recipes
    );
  }
}

而在服务中获取数据的方法是:

fetchData() {
    return this.http.get('https://...firebaseio.com/...json')
      .map((response: Response) => response.json())
      .subscribe(
      (data: Recipe[]) => {
        this.recipes = data;
        console.log(data);
        this.recipesChanged.emit(this.recipes);
      });

正确检索数据,但不会在我的Recipe []上强制转换,实际上返回的对象采用以下形式:

[object Object],[object Object]
   [
      0: {
         [functions]: ,
         __proto__: { },
         description: "Gioco",
         imagePath: "http://....png",
         ingredients: [
            0: {
               [functions]: ,
               __proto__: { },
               amount: 50,
               name: "Silicone",
               Symbol(observable)_g.ds6ymh8xmrz: undefined,
               Symbol(rxSubscriber)_h.ds6ymh8xmrz: undefined
            },
            1: {
               [functions]: ,
               __proto__: { },
               amount: 30,
               name: "Plastica",
               Symbol(observable)_g.ds6ymh8xmrz: undefined,
               Symbol(rxSubscriber)_h.ds6ymh8xmrz: undefined
            },
            length: 2
         ],
         name: "Lego",
         Symbol(observable)_g.ds6ymh8xmrz: undefined,
         Symbol(rxSubscriber)_h.ds6ymh8xmrz: undefined
      },
      1: {
         [functions]: ,
         __proto__: { },
         description: "Peluche",
         imagePath: "http://....png",
         name: "Orsacchiotto",
         Symbol(observable)_g.ds6ymh8xmrz: undefined,
         Symbol(rxSubscriber)_h.ds6ymh8xmrz: undefined
      },
      length: 2
   ]

怎么解决?

提前致谢

1 回答

  • 3

    Output()变量不打算在服务中使用,您应该映射响应并返回Observable

    fetchData() :Observable<Recipes> {
        return this.http.get('https://...firebaseio.com/...json')
          .map((response: Response) => <Recipe[]>response.json())
          });
    

    在你的onInit

    this.recipeService.getRecipes().subscribe(recipes => {
           this.recipes = recipes;
    });
    

    此外,当您使用引用类型作为模型时,使用 interfaces

    export interface Recipe {
            name: string;
            description: string;
            imagePath: string;
            ingredients: Ingredient[];
    
    }
    

相关问题