Cannot read property 'id' of undefined我的 HTML 组件中不断出现错误
<button (click)="getRecipeDetails()">Show</button>
<div>
<div [innerHTML]="recipeInformation.id"></div> <br>
<div [innerHTML]="recipeInformation.title"></div> <br>
<div [innerHTML]="recipeInformation.summary"></div> <br>
<div [innerHTML]="recipeInformation.dishTypes"></div> <br>
</div>
Run Code Online (Sandbox Code Playgroud)
这是我在组件 TS 中制作的代码:
export class AppComponent {
recipeInformation:Recipe;
constructor(private http: HttpClient){}
// Get Recipe Details:
getRecipe(id:any='782698'): Observable<Recipe[]> {
let params = new HttpParams().set('apiKey',Constants.API_KEY)
return this.http.get(URL,{params}).pipe(
map(json: Object) => [json].map(jsonItem => Recipe.fromJson(jsonItem)))
);
}
getRecipeDetails(){
this.getRecipe().subscribe(
recipes => this.recipeInformation = recipes[0]
)
}
Run Code Online (Sandbox Code Playgroud)
这是我的 recipe.ts 类:
export class Recipe{
constructor(public id: number,
public title: string,
public summary: string,
public dishTypes: []) {
}
public static fromJson(json: Object): Recipe {
return new Recipe(
json['id'],
json['title'],
json['summary'],
json['dishTypes']
);
}
}
Run Code Online (Sandbox Code Playgroud)
单击“显示”按钮后,数据可以正常检索,但是在我调用 API 之前和之后,此错误一直显示。
这是因为此时RecipeInformation未定义:
recipeInformation:Recipe;
Run Code Online (Sandbox Code Playgroud)
您可以使用 an*ngIf来提供帮助。
<button (click)="getRecipeDetails()">Show</button>
<div *ngIf="recipeInformation">
<div [innerHTML]="recipeInformation.id"></div> <br>
<div [innerHTML]="recipeInformation.title"></div> <br>
<div [innerHTML]="recipeInformation.summary"></div> <br>
<div [innerHTML]="recipeInformation.dishTypes"></div> <br>
</div>
Run Code Online (Sandbox Code Playgroud)
或者使用安全导航操作符:
<button (click)="getRecipeDetails()">Show</button>
<div>
<div [innerHTML]="recipeInformation?.id"></div> <br>
<div [innerHTML]="recipeInformation?.title"></div> <br>
<div [innerHTML]="recipeInformation?.summary"></div> <br>
<div [innerHTML]="recipeInformation?.dishTypes"></div> <br>
</div>
Run Code Online (Sandbox Code Playgroud)
在此处了解有关安全导航操作员的更多信息
| 归档时间: |
|
| 查看次数: |
34 次 |
| 最近记录: |