I'm new to angular 2 and trying to create a login app which I managed okay however after checking user/pass then redirect to dashboard it reloads the app. Is there a way to not refresh the page using router.navigate?
Edit: it redirects to dashboard first then reloads the page then redirects again back to dashboard.
import { Component } from '#angular/core';
import { Router, ROUTER_DIRECTIVES } from '#angular/router';
#Component({
selector: 'login',
templateUrl: './app/login/views/login.html',
})
export class LoginComponent {
constructor(public router: Router) {}
data = {
username: "",
password: "",
};
loginAction (){
if(this.data.username=="user1" && this.data.password=="pass1"){
console.log('do redirect to dashboard');
this.router.navigate(['dashboard']);
} else {
console.log('Something is wrong with your user/password.');
}
}
}
this.router.navigate(['/dashboard']);
Did you try relativeTo
router.navigate(['dashboard'], {relativeTo: route});
Related
Im am working on an Angular 9 application that uses OneLogin for authentication purposes.
In the auth.component.ts file I have an authentication service that I use in the authentication component:
import { AuthService } from 'path/to/core/services/auth/auth.service';
import { AuthApiService } from 'path/to/core/core/services/auth/auth-api.service';
import { Component, OnInit } from '#angular/core';
import { authCodeFlowConfig } from 'path/to/config/onelogin-api/config-auth.component';
#Component({
selector: 'auth',
templateUrl: './assets/auth.component.html',
styleUrls: ['./assets/auth.component.scss']
})
export class AuthComponent implements OnInit{
constructor(private _authService: AuthService) {
}
startAuthentication() {
this._authService.startAuthentication();
}
ngOnInit(): void {
this.startAuthentication();
}
}
In auth.service.ts I have the startAuthentication() method:
startAuthentication(): Observable<any> {
const {issuer, redirectUri, clientId, responseType, scope} = authCodeFlowConfig;
const url = `someURL`;
this.redirectTo(url);
return of(false);
}
redirectTo(url: string): void {
window.location.href = url;
}
In the app.module.ts file I have this array of routes:
import { AuthService } from './core/services/auth/auth.service';
// more imports
const appRoutes: Routes = [
{
path : 'myroute',
redirectTo: 'myroute'
},
{
path: 'auth',
component: AuthComponent
}
];
In other words, I want the application to reach a certain url if login is successful and otherwise redirect to the login form.
What I want to happen is: when login is sucessful - in other words, when startAuthentication() is executed - there should be a redirect to myroute.
I tried {path: 'auth', component: AuthComponent, startAuthentication:[AuthService]} bit it fails.
What am I doing wrong?
As I don't have any further information about your StartAuthentication method, I'd say that you should inject the router service in your component and navigate using it:
import { Router } from '#angular/router';
...
constructor(
private _authService: AuthService,
private _router: Router) {}
startAuthentication() {
this._authService.startAuthentication();
this._router.navigate(['/', 'myroute']);
}
I am trying to redirect my beta app.
When I open the home page, it should be redirected to another page. I am using window.location on app.component but it's starting to load the components first and then redirecting so it looks kind of weird.
ngOnInit(): void {
this.location = String(window.location);
console.log('this.location);
if (this.location === 'http://localhost:4200/home') {
window.location.replace('https://www.google.com/');
}
}
Use NavigationStart event of router and subscribe it in your constructor like below :
constructor(router:Router) {
router.events.subscribe(event => {
if(event instanceof NavigationStart) { // import { NavigationStart } from '#angular/router';
if (this.location === 'http://localhost:4200/home') {
window.location.replace('https://www.google.com/');
}
}
}
});
import { Router } from '#angular/router';
#Component( {
selector: 'app-viewtables',
templateUrl: './viewtables.component.html',
styleUrls: ['./viewtables.component.css']
} )
export class Home{
constructor(private router: Router ) {
this.router.navigate( ['/secondpage'] );
}
}
I am trying to redirect to a route when user directly paste the url.
I want to direct the user to /en/sell page on hitting the url
http://localhost:3000/en/sell/confirmation
here is my code,
ngOnInit() {
this.storedListing = this.sellerFlow.getSellerFlowObject();
if (this.storedListing === null) {
this.router.navigate(['./']);
}
}
i can see this.router getting executed but the application does not have any change. what is the issue?
You have to use ../ if you want to go from /en/sell/confirmation to /en/sell/:
this.router.navigate(['../']);
See the documentation.
You could instead redirect from your routing:
{
path: 'en/sell/confirmation',
redirectTo: 'en/sell',
pathMatch: 'full'
},
import {OnInit} from '#angular/core';
import {Router} from '#angular/router';
export class AddDisplay {
constructor(private router: Router){}
ngOnInit() {
this.router.navigate(['./SomewhereElse']);
}
}
You have to specify the relativeTo param, as below:
import { ActivatedRoute, Router } from '#angular/router';
constructor(private route: ActivatedRoute, private router: Router) { }
ngOnInit() {
this.storedListing = this.sellerFlow.getSellerFlowObject();
if (this.storedListing === null) {
this.router.navigate(['../'], { relativeTo: this.route });
}
}
I'm creating an app that when the user enters to the page he goes to the default route wich is "Login" page. What I want is based on a condition (if the user has a local storage variable id, a method called isAuthenticaded() returns true if not false) the user must see the "Polls" page instead of "Login" page.
I think two different ways to aprouch this:
1- Change default page: if the method returns true the default page should be "Polls" if not "Login".
2- Redirect the user: if the method returns true the user is redirected to "Polls".
What's the best aprouch to archieve this?
How can I do one or both of the point to get conditional routing?
This is my routing config with the isAuthenticated() method:
import {Component} from 'angular2/core'
import {HTTP_PROVIDERS, Http} from 'angular2/http';
import 'rxjs/Rx'; // load the full rxjs
import {RouteConfig, ROUTER_DIRECTIVES, Router} from 'angular2/router';
import { PollsComponent } from './pollslist/pollslist.component'
import { Login } from './login/login'
#Component({
selector: 'my-app',
templateUrl: 'app/app.component.html',
directives: [ROUTER_DIRECTIVES, Login, PollsComponent],
providers: [HTTP_PROVIDERS]
})
#RouteConfig([
{ path: '/login', name: 'Login', component: Login, useAsDefault: true },
{ path: '/polls', name: 'Polls', component: PollsComponent }
])
export class AppComponent {
isAuthenticated() {
if (localStorage.getItem('id')) {
return true;
} else {
return false;
}
}
}
You can check in
#CanActivate() and navigate to a different route using router.navigate()
or create a custom <router-outlet> where you do this.
For details see https://medium.com/#blacksonic86/authentication-in-angular-2-958052c64492#.f76jyafdn
See also Check if the user logged in on any page change in Angular 2
Router definition has loader parameter:
loader : () => Promise<Type>
that allows to determine component type dynamically and async.
I'm having a bit of trouble getting some routing stuff working in Aurelia.
When a user goes to my app, if they have previously authenticated, I want to redirect them to a landing page. If not, direct to a login page.
I have the authenticated user redirect working fine (app.js -> login.js -> setupnav.js -> landing page).
The problem I have now is:
When a user refreshes a page (http://localhost:8088/aurelia-app/#/landing), the landing route doesn't exist anymore and an error is thrown in the console (ERROR [app-router] Error: Route not found: /landing(…)). I would like to direct the user to login if a route cannot be found.
Does anybody know how I can redirect a user from a missing route to my login page?
Also any comments on how I set the routing up is welcome.
app.js
import {inject} from 'aurelia-framework';
import {Router} from 'aurelia-router';
import {FetchConfig} from 'aurelia-auth';
import {AuthorizeStep} from 'aurelia-auth';
import {AuthService} from 'aurelia-auth';
#inject(Router,FetchConfig, AuthService )
export class App {
constructor(router, fetchConfig, authService){
this.router = router;
this.fetchConfig = fetchConfig;
this.auth = authService;
}
configureRouter(config, router){
config.title = 'VDC Portal';
config.addPipelineStep('authorize', AuthorizeStep); // Add a route filter to the authorize extensibility point.
config.map([
{ route: ['','login'], name: 'login', moduleId: './login', nav: false, title:'Login' },
{ route: '', redirect: "login" },
{ route: 'setupnav', name: 'setupnav', moduleId: './setupnav', nav: false, title:'setupnav' , auth:true}
]);
this.router = router;
}
activate(){
this.fetchConfig.configure();
}
created(owningView: View, myView: View, router){
/* Fails to redirect user
if(this.auth.isAuthenticated()){
console.log("App.js ConfigureRouter: User already authenticated..");
this.router.navigate("setupnav");
}
*/
}
}
login.js
import {AuthService} from 'aurelia-auth';
import {inject} from 'aurelia-framework';
import {Router} from 'aurelia-router';
#inject(AuthService, Router)
export class Login{
constructor(auth, router){
this.auth = auth;
this.router = router;
if(this.auth.isAuthenticated()){
console.log("Login.js ConfigureRouter: User already authenticated..");
this.router.navigate("setupnav");
}
};
heading = 'Login';
email='';
password='';
login(){
console.log("Login()...");
return this.auth.login(this.email, this.password)
.then(response=>{
console.log("success logged");
console.log(response);
})
.catch(err=>{
console.log("login failure");
});
};
}
Redirecting to:
setupnav.js
import {Router} from 'aurelia-router';
import {inject} from 'aurelia-framework';
#inject(Router)
export class Setupnav{
theRouter = null;
constructor(router){
console.log("build setupnav. router:" + this.theRouter);
this.theRouter = router
};
activate()
{
this.theRouter.addRoute( { route: 'landing', name: 'landing', moduleId: 'landing', nav: true, title:'Integration Health' , auth:true});
this.theRouter.addRoute( { route: 'tools', name: 'tools', moduleId: 'tools', nav: true, title:'Integration Tools' , auth:true});
this.theRouter.refreshNavigation();
this.theRouter.navigate("landing");
}
}
To map an unknown route to a specific page, use the mapUnknownRoutes feature:
configureRouter(config, router) {
...
config.mapUnknownRoutes(instruction => {
return 'login';
});
}
That said, it might be easier to keep all auth related logic out of routing and instead use setRoot to set the appropriate root module depending on the user's auth state.
A standard main.js looks like this:
main.js
export function configure(aurelia) {
aurelia.use
.standardConfiguration()
.developmentLogging();
aurelia.start().then(a => a.setRoot());
}
You could change the logic to something like this:
main.js
export function configure(aurelia) {
aurelia.use
.standardConfiguration()
.developmentLogging();
aurelia.start().then(() => {
if (userIsAuthenticated) {
return aurelia.setRoot('app');
}
if (userPreviouslyAuthenticated) {
return aurelia.setRoot('login');
}
return aurelia.setRoot('landing');
});
}
In the example above, the app module is the only module that would configure routes. The login module would be a login page which called setRoot('app') once the user was successfully logged in. The landing page would call setRoot('login') when the user clicked the link/button.
Here's an answer to a related question that might be helpful:
https://stackoverflow.com/a/33458652/725866