angular - Angular无法读取未定义的属性“订阅”
问题描述
我正在尝试使用来自服务器的 json 响应创建动态菜单,但出现此错误:
MenuComponent.html:4 错误类型错误:无法读取 MatMenuTrigger.push../node_modules/@angular/material/esm5/menu.es5.js.MatMenuTrigger.ngAfterContentInit 处未定义的属性“订阅”
当我单击按钮时,它会说:
错误类型错误:无法读取 ViewContainerRef_.push../node_modules/@angular/core/fesm5/core.js.ViewContainerRef_.createEmbeddedView 未定义的属性“createEmbeddedView”
我猜按钮无法创建,因为 json 响应尚未准备好,但我不知道如何修复它。
组件.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) {
}
}
模板.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>
解决方案
你把它复杂化了。这只是 HttpClient.get 的返回类型的问题。显然它没有返回 Observable,您需要阅读该库的文档以了解原因。
您还可以大大简化代码:
export class AppComponent {
readonly branches = this.http
.get('https://demo8635782.mockable.io/branches')
.pipe(
map((data) => data as Branches),
map(({branches}) =>branches),
shareReplay(),
);
constructor(private http: HttpClient) {}
}
<button mat-button [matMenuTriggerFor]="branchesMenu">Branches</button>
<mat-menu #branchesMenu="matMenu">
<button mat-menu-item *ngFor="let branch of (branches | async)">{{branch.name}}</button>
</mat-menu>
编辑:不,完全错误。正如 Daniel Caldera 在下面指出的那样,实际问题是 mat-menu-item 的 matMenuTriggerFor。
其他问题:
- 您需要导入 BrowserAnimationsModule
- 您需要导入操作符(map、shareReplay)
- 您需要在 CSS 中包含主题
- 正如我最初建议的那样,您不应该取消引用异步
这是我的工作版本。
推荐阅读
- html - 全屏模式下可见滚动条
- javascript - 确定 iFrame 元素是否作为包装器中的子元素存在
- sql-server - 测量运行 SQL 作业的时间,如果超过一定数量则启动另一个
- azure - Azure 数据工厂:当链接服务被参数化时,无法将内联数据集用于 Common Data Model
- c++ - 图中没有匹配的函数调用 boost::get
- javascript - 在 d3.js v5 上旋转树图(从水平到垂直)
- css - Glade 样式不适用于 C 中编译的 GTK 程序
- html - 如何创建响应邮件
- node.js - 获取未为 yargs.getHelp() 定义的函数
- mysql - 如何用另一个表中的列中的数据替换表中的一列中的数据?