Angular.js 6.1.0 - 变量未传递给视图

Angular.js 6.1.0 - Variable not being passed to the view

我正在通过教程修改我的 angular:

https://www.youtube.com/watch?v=z4JUm0Bq9AM

https://coursetro.com/posts/code/154/Angular-6-Tutorial---Learn-Angular-6-in-this-Crash-Course

我的边栏有这两个文件:

sidebar.component.ts

import { Component, OnInit } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';

@Component({
  selector: 'app-sidebar',
  templateUrl: './sidebar.component.html',
  styleUrls: ['./sidebar.component.scss']
})
export class SidebarComponent implements OnInit {

  currentUrl: string;

  constructor(private router: Router) {
    router.events.subscribe((_: NavigationEnd) => this.currentUrl = _.url);
  }

  ngOnInit() {
  }

}

sidebar.component.ts

<nav>
  <ul>
    <li>
      <a routerLink="" [class.activated]="currentUrl == '/'">
        <i class="material-icons">supervised_user_circle</i>
      </a>
    </li>
    <li>
      <a routerLink="posts" [class.activated]="currentUrl == '/posts'">
        <i class="material-icons">message</i>
      </a>
    </li>
  </ul>
</nav>

问题是 currentUrl 没有传递给视图。我检查并仔细检查了我的代码是否与视频中显示的完全一致,并直接从 tut 的文本版本粘贴,但无济于事。

我已经确认 1,它正在被设置(通过 console.log)和 2,它没有被传递到视图(通过使用 [=15= 将变量转储到页面) ]).

如果有人能指出问题所在,我将不胜感激。

在原始代码中,即使您将事件键入 NavigationEnd,并非所有事件实际上都是 NavigationEnd 事件,因此它们并非都具有 url 属性.

我们可以在此处添加 .filter 运算符以过滤掉任何不是 NavigationEnd 事件的事件。这样,它们都应该有一个 url 属性,这样 currentUrl 就不会被覆盖为 undefined

  constructor(private router: Router) {
    router.events.pipe(
      filter((evt) => evt instanceof NavigationEnd)
    ).subscribe((_: NavigationEnd) => {
      this.currentUrl = _.url;
    });

Here is a fork of the StackBlitz