angular - Angular 6在渲染模板之前等待服务响应
问题描述
我无法解决这个问题。有人知道这里发生了什么吗?
我的 CategoryService 是
getCategory(): Observable<Category[]> {
// return this.http.get<Category[]>("/category");
return this.http.get<Category[]>(this.endpoint)
}
这是我的编辑类别组件
import { Component, OnInit } from '@angular/core';
import { CategoryService, Category } from '../services/category.service';
import { Router, ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-edit-category',
templateUrl: './edit-category.component.html',
styleUrls: ['./edit-category.component.scss']
})
export class EditCategoryComponent implements OnInit {
constructor(private categoryService : CategoryService, private router: ActivatedRoute ) { }
category : Category;
ngOnInit() {
this.router.params.subscribe(params => {
this.categoryService.getCategory().subscribe((data : Category[]) => {
this.category = data.filter(res => {
return res.id == params["id"]
})[0];
console.log(this.category)
});
});
}
}
我需要在我的 edit-category-component.html 中调用 category 。
<p>
{{category.Adi}}
</p>
我可以这样做,但在那之后或者同时浏览器说 4 次(我有 4 条记录)。但是我的代码在那 4 个错误记录之后显示。代码有效,那么这些错误是如何产生的。
ERROR TypeError: Cannot read property 'Adi' of undefined
我是角度的新手。这看起来像 Promise 还是 ngOnInit?对不起,我真的不知道我怎么能写出真正的问题。
解决方案
您可以改用 null 安全运算符:
<p>
{{category?.Adi}}
</p>
这将防止您在类别为空/未定义时看到的错误。您可以在此处阅读更多信息:https ://angular.io/guide/template-syntax#the-safe-navigation-operator----and-null-property-paths
推荐阅读
- javascript - 使用 jQuery 以编程方式在上传按钮中设置文件名
- javascript - MP3 文件不在自定义控件中播放
- javascript - Sequelize查找多个表
- video - 如何使用静音 = 0 自动播放 Vimeo 视频?
- firebase - FirestoreRecyclerAdapter 显示 Nothong
- c# - 隐藏在软键盘 UWP 后面的 ContentDialog
- node.js - npm 命令给出语法错误:意外令牌(mac)
- php - TCPDF - 删除 2 个表之间的空间 (PHP)
- python - 如何在 python alexa 中使用 AMAZON.Repeat Intent?
- vba - 将第一个列表的每个元素与第二个列表的所有元素进行比较以找到匹配项