首页 > 解决方案 > Ionic3 中的订阅不返回任何内容

问题描述

我正在使用 Ionic3 做一个食谱应用程序项目,当我尝试从我的服务中获取数据时遇到了问题。

这是我的服务:

export interface Recipe{
    id: number;
    name: string;
    image: string;
    time: number;
    ingredients: string[];
    elaboration: string[];
}

export interface Data{
    category: string;
    recipes: Recipe[];
}

@Injectable()
export class RecipeService{

    constructor(){

    }

    data(): Data[]{
         const data = [
               {"category": "desserts", "recipes": [Array of recipes here]},
               {"category": "desserts", "recipes": [Array of recipes here]},
               {"category": "desserts", "recipes": [Array of recipes here]}
            ];

         return data;
     }

    getData(): Subject<Data[]>{

        const data = new Subject<Data[]>();


        data.next(this.data());


        return data;
    }

我尝试在我的页面中获取这些数据,如下所示:

@Component({
  selector: 'page-recipes-categories',
  templateUrl: 'recipes-categories.html',
})
export class RecipesCategoriesPage implements OnInit, OnDestroy {

  private subscription: Subscription;
  public categories: string[];
  public data: Data[];

  constructor(public navCtrl: NavController, 
              public navParams: NavParams,
              private recipeService: RecipeService) {
  }

  ngOnInit(){


    this.subscription = this.recipeService.getData().subscribe((data: Data[]) => {
      this.data = data;
     })


  }

  ngOnDestroy(){

  }

}

当我制作 console.log(this.data) 时,我得到“未定义”。我有其他类似的服务并且工作正常。我真的不明白发生了什么。

PD:所有的进口都很好。

标签: ionic3

解决方案


推荐阅读