我正在尝试使用服务器的json响应创建动态菜单,但出现此错误:
MenuComponent.html:4错误TypeError:无法读取未定义的属性“ subscribe” 在MatMenuTrigger.push ../ node_modules/@angular/material/esm5/menu.es5.js.MatMenuTrigger.ngAfterContentInit
当我单击按钮时,它说:
错误TypeError:无法读取未定义的属性'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>
答案 0 :(得分:3)
您过于复杂了。这只是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。
其他问题:
Here是我的工作版本。
答案 1 :(得分:2)
我在此stackblitz中解决了 我使用了正确的材质版本并按角度更新了相关性,使用了将按钮包裹在ngIf中的模板中的observable,还删除了mat-menu-item的matMenuTriggerFor并在app.module中导入BrowserAnimationsModule。
编辑添加子菜单,为此,您必须在ngFor迭代内创建子菜单。
答案 2 :(得分:0)
我有类似的问题。登录后刷新我的令牌。 后端需要令牌,因此必须使用有效令牌进行请求。
确保您的请求中包含有效令牌。
查看您的后端。