My goal is to develop an Angular (version 11.2.9) routing service that will facilitate automatic redirection of users from one page to another within the site.
For instance, a guest user visiting the site can log in to their account by clicking on a button that directs them to the "Log in page." Once logged in, the button disappears, but the user can still access the login page by entering "/login" in the address bar. I want to set up automatic redirection from "/login" and similar pages to specific predetermined sites.
Here's a snippet from prijava.component.ts:
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { AuthenticationService } from '../../services/authentication.service';
import { RedirectService } from '../../services/redirect.service';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
public href: string = "";
constructor(
private router: Router,
private authService: AuthenticationService,
private redirectService: RedirectService,
) {}
/*Other variables, etc. Sending the data*/
ngOnInit() {
this.redirectService.redirectUnwanted();
}
}
The redirect service being developed:
redirect.service.ts:
import { Router} from '@angular/router';
import {AuthenticationService} from './authentication.service';
export class RedirectService {
constructor(
private router: Router,
private authService: AuthenticationService
) { }
//Redirect unwanted sites
public redirectUnwanted(): void{
//Check if user is logged in
if(this.authService.isLoggedIn()){
//Redirect from /login, /registration, /passwordRecovery
console.log(this.router.url);
}
}
}
When clicking on a routerLink with '/login', an empty page is displayed along with the following error message:
ERROR Error: Uncaught (in promise): NullInjectorError: R3InjectorError(AppModule)[RedirectService -> RedirectService -> RedirectService]:
NullInjectorError: No provider for RedirectService! ... (error continues)
I have tried various solutions such as adding a 'providers' field in the @Component declaration of the login component, but it resulted in a different error about not having an Angular decorator.
In addition, attempts to use an AuthGuard implementing CanActivate also led to errors regarding property assignment and type mismatch.
Alternatively, there is a history service available. Is there any way to utilize or improve upon the functionality provided by this service?
history.service.ts:
import { Injectable } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
import { filter } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class HistoryService {
private urlAddresses: string[] = [];
constructor(private router: Router) {
this.router.events
.pipe(filter(event => event instanceof NavigationEnd))
.subscribe((event: NavigationEnd) => {
const url = event.urlAfterRedirects;
this.urlAddresses = [...this.urlAddresses, url];
})
}
public getPreviousUrl(): string {
const length = this.urlAddresses.length;
return length > 1 ? this.urlAddresses[length - 2] : '/';
}
public getPreviousUrlExcludingSelected(): string {
const exclude: string[] = ['/register', '/login', '/forgotPassword','/resetPassword/:email',
'/users/:userId', ];
const filtered = this.urlAddresses.filter(url => !exclude.includes(url));
const length = filtered.length;
return length > 1 ? filtered[length - 1] : '/';
}
}
In conclusion, what is the correct approach to implement a robust and error-free redirection service within an Angular application?