访问 *ngIf 内的 url 路径

Access url path inside *ngIf

我需要在 *ngIf 中访问我的 url 的路径。我试过以下方法:

import { ActivatedRoute } from '@angular/router';

@Component({
    selector: 'my-app',
    providers: [],
    templateUrl: 'app.component.html'
})
export class AppComponent implements OnInit {

    constructor(public route: ActivatedRoute) {

    }
}

在我的 HTML/Pug 中:

div(*ngIf='route.firstChild?.url?.value[1]?.path == "somePath"')

当我使用 angular cli 构建它时它确实有效,但是当我尝试使用 aot 构建它时,我收到以下错误:Property 'value' does not exist on type 'Observable<UrlSegment[]>'

似乎不​​允许我直接访问内部可观察对象的值 *ngIf

不是不能直接访问observable的值,而是浏览器初始化view的时候observable的值是undefined。这通常是 Observables 的工作方式,因为它们本质上是异步的。

我能想到的两种解决方法:

  1. 使用 Angular 2 的异步管道:https://angular.io/api/common/AsyncPipe。这将允许视图等待可观察对象提供的下一个值,并且 AOT 不应该抱怨。
  2. 在构造函数或 ngOnInit 生命周期挂钩中订阅路由值,将该值分配给组件中的变量 class,并在 ngIf 语句中使用该组件绑定变量 (如果你走这条路,请确保将变量初始化为 false,否则 AOT 可能会抱怨该值未定义)