首页 > 解决方案 > 更改路线后角度组件属性值消失

问题描述

我是 Angular 开发的新手。我试图构建一个食谱列表组件,您可以在其中通过调用 api 并将返回的食谱对象推送到列表中来在列表中添加食谱项目。它工作正常。但是,一旦我将路线更改为其他路线,一切都会重置。这是代码recipe-list.component.ts

import { Component, OnInit } from '@angular/core';
import { RecipeModel } from '../recipe.model';
import { axiosClient } from '../../axiosApi/axiosApi';

@Component({
  selector: 'app-recipe-list',
  templateUrl: './recipe-list.component.html',
  styleUrls: ['./recipe-list.component.css']
})

export class RecipeListComponent implements OnInit {
  private axiosClient: axiosClient;
  recipeList: RecipeModel[] = [];
  constructor(axiosClient: axiosClient) { 
    this.axiosClient = axiosClient;
  }

  ngOnInit(): void {
  }

  getRandomRecipe(): void {
    this.getRandomRecipeHelper()
    .then(recipe => {
      this.recipeList.push(recipe);
    });
  }

  async getRandomRecipeHelper(): Promise<RecipeModel> {
    try {
      let recipeObject = await this.axiosClient.get<any>({
        url: "https://www.themealdb.com/api/json/v1/1/random.php",
      });
      let meal_info: any = recipeObject.meals[0];
      let title = meal_info['strMeal'];
      let body = meal_info['strInstructions'];
      let category = meal_info['strCategory'];
      let area = meal_info['strArea'];
      let thumbnail = meal_info['strMealThumb'];
      let link = meal_info['strYoutube'];
      let ingredients: {name: string, measure: string}[] = [];
      for (let i = 1; i <= 20; i++) {
        if (meal_info['strIngredient' + i] !== "" && meal_info['strMeasure' + i] !== "") {
          ingredients.push({'name': meal_info['strIngredient' + i], 'measure': meal_info['strMeasure' + i]});
        }        
      }
      let recipe = new RecipeModel(title, body, category, area, thumbnail, link, ingredients);
      return new Promise<RecipeModel>((resolve, reject) => {resolve(recipe)});
    }
    catch(error) {
      console.error(error);
    }
  }
  
}

我在 arecipe.component.ts中有配方列表组件/recipes,其中还有/shopping/home。如果有人可以帮助我解决这里的问题,那就太好了。谢谢你。

标签: angularangular2-routing

解决方案


推荐阅读