首页 > 解决方案 > 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>

堆栈闪电战

标签: angular

解决方案


你把它复杂化了。这只是 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。

其他问题:

  1. 您需要导入 BrowserAnimationsModule
  2. 您需要导入操作符(map、shareReplay)
  3. 您需要在 CSS 中包含主题
  4. 正如我最初建议的那样,您不应该取消引用异步

是我的工作版本。


推荐阅读