angular - 更改路线后角度组件属性值消失
问题描述
我是 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
。如果有人可以帮助我解决这里的问题,那就太好了。谢谢你。
解决方案
推荐阅读
- unix - 根据另一个文件中给出的 ID 从 SDF 文件中按顺序提取分子
- python - 如何使用openpyxl更改excel电子表格中每隔一行的字体颜色?
- r - 选择线性回归线的颜色
- css - HTML 表格单元格宽度
- html - 我想控制降价列表
- javascript - 捕获用户从视频数组播放的视频 id
- cassandra - 如何在使用创建密钥空间时修复“没有可用的主机”
- intellij-idea - Intellij:如何从终端使编辑器成为焦点?
- java - 为什么这个 if 语句不返回布尔值?
- snakemake - 是否可以使用命令行标志启用/禁用某些 Snakemake 规则