代码之家  ›  专栏  ›  技术社区  ›  Jack BeNimble

角度7-布尔值始终为true

  •  1
  • Jack BeNimble  · 技术社区  · 6 年前

    我在Angular7中有一个布尔值,用来在对象构造函数中设置一个值。布尔值作为参数传递,我在本地存储它。

    但是,由于某些原因,布尔值始终计算为true。

    以下是相关代码:

      ngOnInit() {
        this.id = this.route.snapshot.params['id'];
        this.showPersonal = this.route.snapshot.params['showPersonal'];
        console.log("ngOnInit, this.id: " +  this.id);
        console.log("ngOnInit, this.showPersonal: " +  this.showPersonal);
        // if showPersonal is true, workRelated i.e. last item in constructor, is false
    
        if (this.showPersonal){
          console.log("showPersonal is true, setting work related to false")
          this.showWorkRelated = false;
        }
        else {
          console.log("showPersonal is false, setting work related to true")
          this.showWorkRelated = true; 
        }
    
    console.log("this.showWorkRelated: " + this.showWorkRelated)
    

    这是输出:

    todo.component.ts:28 ngOnInit, this.showPersonal: false
    todo.component.ts:32 showPersonal is true, setting work related to false
    todo.component.ts:40 this.showWorkRelated: false
    

    我试过很多不同的方法,但总被认为是真的。这个密码怎么了?

    1 回复  |  直到 6 年前
        1
  •  1
  •   Cuong Le Ngoc    6 年前

    看起来像是你的 this.route.snapshot.params['showPersonal'] 返回字符串 false 所以 if (this.showPersonal) 被认为是真的。

    你应该试着用 typeof this.showPersonal 查看变量的类型。