我已经使用以下两个代码段根据我的路由在控制台中获取editmode变量的值,我认为两者应该工作相同。但是第一个给出正确的输出,第二个总是显示正确。无法弄清楚这里出了什么问题
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Params } from '@angular/router';
@Component({
selector: 'app-recipe-edit',
templateUrl: './recipe-edit.component.html',
styleUrls: ['./recipe-edit.component.css']
})
export class RecipeEditComponent implements OnInit {
id:number;
editMode:boolean=false;
constructor(private route:ActivatedRoute) { }
ngOnInit() {
this.route.params.subscribe(
(params:Params) =>{
this.id = +params['id'];
this.editmode = (params['id'] != null);
console.log(this.editmode);
}
);
}
}
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Params } from '@angular/router';
@Component({
selector: 'app-recipe-edit',
templateUrl: './recipe-edit.component.html',
styleUrls: ['./recipe-edit.component.css']
})
export class RecipeEditComponent implements OnInit {
id:number;
editMode:boolean=false;
constructor(private route:ActivatedRoute) { }
ngOnInit() {
this.route.params.subscribe(
(params:Params) =>{
this.id = +params['id'];
this.editmode = (this.id != null);
console.log(this.editmode);
}
);
}
}
答案 0 :(得分:0)
这更像是找到两者之间的区别。我敢打赌params['id']
不是number
或numberic
,而做+param['id']
会给你NaN
,它不等于null
。
在第一个代码中,如果要进行以下更改,您将获得与第二个代码相同的输出。
this.route.params.subscribe(
(params:Params) =>{
this.id = +params['id'];
this.editmode = (+params['id'] != null); // change here
console.log(this.editmode);
}
);