In my angular application I Have fetched the data from the server and it is in json format like
jsondata = {
Id: 16531914,
EmailId: "[email protected]"
}
And my requirement is if the jsondata(coming from server ) has the Id then I have to navigate to the dashboard page else I have to go to the login page
CodePudding user response:
you can simply use an if chek
if(jsondata.Id) return this.router.navigate([...other routes, jsondata.Id])
this.router.navigate(['/login'])
CodePudding user response:
When the JSON has been parsed into a JS object (via JSON.parse or Angular's HttpClient calling that internally) you can check if a field exists by comparing it against null:
if (jsondata.Id != null) {
// navigate(etc)
}
Just doing if (jsondata.Id) won't work if the id field is 0 because 0 is a falsy value in JS. Doing a lose comparison to null (!= null) will capture both undefined and null but not 0.
CodePudding user response:
You can also check, when the object is available or not
goto = (page) => {
this.router.navigate([page]);
}
jsondata?.id ? this.goto(jsondata.id.toString()) : this.goto('login')
