【发布时间】:2018-07-03 18:52:05
【问题描述】:
我正在尝试使用来自服务器的 json 响应创建一个动态菜单,但出现此错误:
MenuComponent.html:4 错误类型错误:无法读取未定义的属性“订阅” 在 MatMenuTrigger.push../node_modules/@angular/material/esm5/menu.es5.js.MatMenuTrigger.ngAfterContentInit
当我点击按钮时,它会说:
错误类型错误:无法读取未定义的属性“createEmbeddedView” 在 ViewContainerRef_.push../node_modules/@angular/core/fesm5/core.js.ViewContainerRef_.createEmbeddedView
我猜按钮无法创建,因为 json 响应尚未准备好,但我不知道如何修复它。
Component.ts
export class MenuComponent implements OnInit {
branchList: Branches = new Branches(); //read somewhere that I need to initialize, not sure
ngOnInit(): void {
this.http.get('http://demo8635782.mockable.io/branches').subscribe((data: any) => {
if (data === null) {
console.log('api request returns empty!');
}
this.branchList = data;
});
}
constructor(private breakpointObserver: BreakpointObserver, private http: HttpClient) {
}
}
Template.html
<button mat-button [matMenuTriggerFor]="branchesMenu">Branches</button>
<mat-menu #branchesMenu="matMenu">
<div *ngFor="let branch of branchList?.branches">
<button mat-menu-item [matMenuTriggerFor]="branch?.name">{{branch.name}}</button>
</div>
</mat-menu>
【问题讨论】:
-
您不确定的那一行.. 从
branchList: Branches = new Branches();更改为branchList: Branches;怎么样?它会改变错误吗? ...而且我从未见过为 ngOnInit 声明的类型 - 不需要 -
不,它不会改变任何东西,我从这里看到了它:link
-
@Igor 我添加了示例
-
返回数据的接口不能和branchList的接口相似,否则会报错。
标签: angular