【问题标题】:Angular.js 6.1.0 - Variable not being passed to the viewAngular.js 6.1.0 - 变量未传递给视图
【发布时间】:2019-02-02 08:12:42
【问题描述】:

我正在通过教程修改我的角度:

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,它没有被传递到视图(通过使用 {{ currentUrl }} 将变量转储到页面)。

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

【问题讨论】:

  • 您能否创建一个 StackBlitz 来重现该问题?在您提供的代码中,如果您要在模板中使用{{currentUrl}},则没有理由不显示它
  • 当我记录事件时,最新的总是未定义的
  • 是的,我也发现了,我尝试仅在 _.url 为真时设置它,但它仍然没有传递给视图。
  • 我也试过禁用router.events.subscribe((_: NavigationEnd) =&gt; this.currentUrl = _.url);并直接设置变量,在视图中仍然是空的。

标签: javascript angular javascript-framework


【解决方案1】:

在原始代码中,即使您将事件键入为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

【讨论】:

  • ERROR ReferenceError: filter is not defined
  • 您需要导入:import { filter } from 'rxjs/operators';(假设您在 StackBlitz 中使用 rxjs 6)
  • 是的,我刚刚在堆栈闪电战中发现了这一点。这似乎确实有效。您能否快速解释一下为什么它以前不起作用(以及为什么禁用动态内容并将 currentUrl 直接设置为 '/' 失败)。
  • 我已经添加了一个解释器,但是disabling the dynamic stuff and directly setting currentUrl to '/' failed 是什么意思?你能重现这种行为吗?
  • 空构造函数和currentUrl: string = '/';(在constructor() 中设置它似乎确实有效)。
猜你喜欢
  • 1970-01-01
  • 2016-06-18
  • 1970-01-01
  • 2011-09-05
  • 2012-04-25
  • 1970-01-01
  • 1970-01-01
  • 2016-03-26
  • 2011-10-01
相关资源
最近更新 更多