0

Inside an Angular project I have a function. When I run it, I expect to go to the home.

Inside my function I have a condition, if is true I want to redirect.

 if (condition) {
     location.url('/home');
     // code...
 }
1
  • I would suggest reading angular's router guide. Angular should handle all of the router changes. By doing location.href = ... you are using the native js redirect, which forces your app to refresh. (which hurts user experience) Commented Dec 19, 2017 at 19:54

3 Answers 3

2
constructor(private router: Router) { }

 if (condition) {
      this.router.navigate(['/home']);
 }
Sign up to request clarification or add additional context in comments.

Comments

1

Slightly confused what you mean by "redirect". If you have a condition that determines the final location, then you can just use go to one or the other.

if(location) {
   $location.url('/home');
} else {
   $location.url('/otherDestination');
}

If you mean a true redirect that reflects in the window history, read about the $location.replace function provided by AngularJS. Scroll down to the section labeled 'Replace method'. Hope this helps!

$location.url('/otherDestination').replace();

3 Comments

i have a condition: if (task.id == id ) { location.url('/home'); // code... }
Can you please clarify? Are you asking how to redirect if task.id != id?
The condition isn't important. I was just confused on what you were asking. If you need to navigate to a different page if task.id != id then you could have an else statement where you have the location.url go to a different page (like in the answer if/else statement) right? I apologize if I'm misunderstanding the question but it seems pretty straightforward.
0

Yyou can always use JS

window.location.href = 'xyz';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.