angular redirect to url

Angular 5 redirect to previous page after sign in.

When I am hitting a url manually, if it is not logged in, it will redirect to login page but after login, it should redirect to url which entered but now I just can redirect to homepage by using this:

5 Answers 5

When you redirect to the login page with a guard, you could put the source url in the queryParams as such:

After you log in you can get the original page url from the query params:

You can send the URL before going to the homepage and use it there

So then in your login Component you can access to the queryParams like this

for me queryParams not work properly because if the user goes to log in, and next go to the signup route, so you need to preserve query params. But if you have more steps before login, or user refreshes the page, or the internet was bad on a subway or something else happened and he lost his params and will be redirected to who knows. But if you set needed URL to redirect to localStorage and after login/signup/someelse step you can redirect him to needed URL previously delete the string from localStorage.

Источник

I’m trying to Open a new page when user clicks on a link. I can’t use Angular 2 Router, because it doesn’t have any functionalities to redirect to an external URL.

so, i’m using window.location.href=». «;

9 Answers 9

One caveat on using window.open() is that if the url that you pass to it doesn’t have http:// or https:// in front of it, angular treats it as a route.

Читайте также:  К чему снится пожар от молнии во сне

To get around this, test if the url starts with http:// or https:// and append it if it doesn’t.

Another possible solution is:

I want to share with you one more solution if you have absolute part in the URL

and url will be opened in new tab.

you can do like this in your typescript code

In your html code add an anchor tag and pass that variable(location)

Suppose you have url like this www.google.com without http and you are not getting redirected to the given url then add http:// to the location like this

This will resolve the issue, here you don’t need to use DomSanitizer. Its work for me

To solve this issue more globally, here is another way using a directive:

then it’s as simple as using it like this:

and don’t forget to declare the directive in your module.

Источник

How to redirect Page in Angular?

I’m Trying to redirect one component to another (like page redirect)

app-routing.module.ts

top-header.component.html

AppComponent.html

4 Answers 4

You can use router.navigate function of the Router class. Just import Router from @angular/router and create a object for it in the constructor(private router: Router) and use router.navigate([‘/roles’]);

Your app-routing.module.ts is fine. Now, in your component you can do Import Router and use it to redirect.

And in your component.html just call that redirect() function

just add this path in your app-routing.module.ts file so that it can know the path:

Example usage in a contoller:

Not the answer you’re looking for? Browse other questions tagged html angular or ask your own question.

Linked

Related

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Читайте также:  на ногах тонкие сосуды что делать

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.9.16.40224

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Как перенаправить на внешний URL в Angular2?

каков метод перенаправления пользователя на полностью внешний URL-адрес в Angular 2. Например, если мне нужно перенаправить пользователя на сервер OAuth2 для аутентификации, как это сделать?

9 ответов

вы можете использовать это-> window.location.href = ‘. ‘;

это изменит страницу на то, что вы хотите..

угловой подход к ранее описанным методам заключается в импорте DOCUMENT С @angular/common (или @angular/platform-browser в угловой

некоторые-страницы.деталь.ТС

некоторые-страницы.деталь.HTML-код

Проверьте plateformBrowser РЕПО для получения дополнительной информации.

решение, как сказал Деннис Смолек, это смертельно просто. Set window.location.href к URL, на который вы хотите переключиться, и он просто работает.

например, если у вас был этот метод в файле класса вашего компонента (контроллер):

тогда вы можете назвать это довольно просто с соответствующим (click) вызовите кнопку (или что-то еще) в вашем шаблоне:

мне нужно à target= «_blank», вы можете использовать окно.открыть:

Если вы использовали крюк жизненного цикла OnDestry, вам может быть интересно использовать что-то подобное перед вызовом window.местоположение.с href=.

это вызовет обратный вызов OnDestry в вашем компоненте, который вам может понравиться.

где вы найдете маршрутизатор.

—редактировать— К сожалению, я мог ошибаться в приведенном выше примере. По крайней мере, это не работает, как ожидаемых в моем производстве код теперь-так, пока у меня нет времени, чтобы исследовать дальше, я решаю это так (так как моему приложению действительно нужен крючок, когда это возможно)

Читайте также:  мерджан ага великолепный век что с ним

В основном маршрутизация на любой (фиктивный) маршрут, чтобы заставить крюк, а затем перемещаться по запросу.

Я сделал это, используя угловое расположение 2, так как я не хотел сам манипулировать глобальным объектом окна.

Это можно сделать так:

я использовал окно.местоположение.href =’http://external-url’;

для меня перенаправления работали в Chrome, но не работали в Firefox. Следующий код решил мою проблему:

после отрывания моей головы решение состоит в том, чтобы просто добавить http:// в href.

в своем компонент.ТС

в своем компонент.HTML-код

Источник

Angular URL Redirect

When user entry home or tab-navigation app must go on the login page.

This logic work when entry is » or something like this ‘dfd45657d’. Why not work for home and tab-navigation?

3 Answers 3

First of all, you need to create associate component for login.

Second, matchpath doesn’t affect you here. so whether you keep it or not, no effect.

if you had a login url in your routes, my guess will be that since login match ‘**’ it may have something to do with two succesive redirection.

but if your really did not add a login url, you may need to add one.

Not the answer you’re looking for? Browse other questions tagged angular typescript or ask your own question.

Related

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.9.16.40224

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Образовательный портал