Angular 7 - 布尔值始终计算为真
Angular 7 - boolean always evaluates to true
我在 Angular 7 中有一个布尔值,我用它来在对象构造函数中设置一个值。布尔值作为参数传递,我将其存储在本地。
但是,由于某种原因,布尔值的计算结果始终为真。
这里是有问题的代码:
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
我尝试了很多不同的方法,但它的计算结果总是正确的。这段代码有什么问题?
看起来你的 this.route.snapshot.params['showPersonal']
return 是一个字符串 false
所以 if (this.showPersonal)
被视为 true。
你应该尝试使用 typeof this.showPersonal
来查看变量的类型。
我在 Angular 7 中有一个布尔值,我用它来在对象构造函数中设置一个值。布尔值作为参数传递,我将其存储在本地。
但是,由于某种原因,布尔值的计算结果始终为真。
这里是有问题的代码:
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
我尝试了很多不同的方法,但它的计算结果总是正确的。这段代码有什么问题?
看起来你的 this.route.snapshot.params['showPersonal']
return 是一个字符串 false
所以 if (this.showPersonal)
被视为 true。
你应该尝试使用 typeof this.showPersonal
来查看变量的类型。