我无法解决此问题。有人知道这里会发生什么吗?
我的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>
这将防止当category为null / undefined时出现的错误。您可以在此处了解更多信息:https : //angular.io/guide/template-syntax#the-safe-navigation-operator----and-null-property-paths
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句