I am trying to write an Angular (11.2.9) routing service, which primarily enables me to automatically route the use from one site to a specified one.
For example: when a guest user comes to the site has can log into his account (if he is already registered) via a button that routes him to the "Log in page". When he is logged into the site the is no before mentioned button, but the user can still Log in when he types "/prijava" into the address bar. I would like to auto redirect from "/prijava" (and other similar sites) him to a specified site (for now hardcoded).
prijava.component.ts:
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { AvtentikacijaService} from '../../storitve/avtentikacija.service';
import { PovezavaService } from '../../storitve/povezava.service';
import { UsmerjanjeService} from '../../storitve/usmerjanje.service';
import { ZgodovinaService } from '../../storitve/zgodovina.service';
@Component({
selector: 'app-prijava',
templateUrl: './prijava.component.html',
styleUrls: ['./prijava.component.css']
})
export class PrijavaComponent implements OnInit {
public href: string ="";
constructor(
private usmerjevalnik: Router,
private avtentikacijaStoritev: AvtentikacijaService,
private usmerjanjeStoritev: UsmerjanjeService,
) {}
/*Other variables, etc. Sending the data*/
ngOnInit() {
//the routing service is called here ,I'd like to check as soon as posibile for these conditions
this.usmerjanjeStoritev.preusmeriNezazelene();
}
}
The redirect service that I am writing:
usmerjanje.service.ts:
import { Router} from '@angular/router';
import {AvtentikacijaService} from './avtentikacija.service';
export class UsmerjanjeService {
constructor(
private usmerjevalnik: Router,
private avtentikacijeStoritev: AvtentikacijaService
) { }
//redirect unwanted sites,
public preusmeriNezazelene():void{
//if the user is logged in
if(this.avtentikacijeStoritev.jePrijavljen()){
//redirect from /login, /registration, /passwordRecovery
//just for printing something out
console.log(this.usmerjevalnik.url);
}
}
}
However, when I click a routerLink with /prijava (login), I get an empty site and the following error.
ERROR Error: Uncaught (in promise): NullInjectorError: R3InjectorError(AppModule)[UsmerjanjeService -> UsmerjanjeService -> UsmerjanjeService]:
NullInjectorError: No provider for UsmerjanjeService! NullInjectorError: R3InjectorError(AppModule)[UsmerjanjeService -> UsmerjanjeService -> UsmerjanjeService]:
NullInjectorError: No provider for UsmerjanjeService! at NullInjector.get (core.js:11102) at R3Injector.get (core.js:11269) at R3Injector.get (core.js:11269) at R3Injector.get (core.js:11269) at NgModuleRef$1.get (core.js:25299) at Object.get (core.js:25013) at lookupTokenUsingModuleInjector (core.js:3389) at getOrCreateInjectable (core.js:3501) at Module.ɵɵdirectiveInject (core.js:14693) at NodeInjectorFactory.PrijavaComponent_Factory [as factory] (prijava.component.ts:14) at resolvePromise (zone-evergreen.js:798) at resolvePromise (zone-evergreen.js:750) at zone-evergreen.js:860 at ZoneDelegate.invokeTask (zone-evergreen.js:399) at Object.onInvokeTask (core.js:28561) at ZoneDelegate.invokeTask (zone-evergreen.js:398) at Zone.runTask (zone-evergreen.js:167)
enter code here
at drainMicroTaskQueue (zone-evergreen.js:569) at ZoneTask.invokeTask [as invoke] (zone-evergreen.js:484) at invokeTask (zone-evergreen.js:1621)`
I tried:
Including "providers" field in the @Component declaration of prijava.ts, just throws another error: The class 'UsmerjanjeService' cannot be created via dependency injection, as it does not have an Angular decorator. This will result in an error at runtime.
Either add the @Injectable() decorator to 'UsmerjanjeService', or configure a different provider (such as a provider with 'useFactory').
Implementig an AuthGuard implementing CanActivate the the canActictavate gives me the following error which at this point I don't understand :
Property 'canActivate' in type 'AuthGuard' is not assignable to the same property in base type 'CanActivate'.
Type '() => void' is not assignable to type '(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => boolean | UrlTree | Observable<boolean | UrlTree> | Promise<...>'.
Type 'void' is not assignable to type 'boolean | UrlTree | Observable<boolean | UrlTree> | Promise<boolean | UrlTree>'.ts`
Alternatively I've also a history service Is there anything I can (re)use from that script?
zgodovina.service.ts:
import { Injectable } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
import { filter } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class ZgodovinaService {`
private urlNaslovi: string[] = [];
constructor(private usmerjevalnik: Router) {
this.usmerjevalnik.events
.pipe(filter(dogodekUsmerjanja => dogodekUsmerjanja instanceof NavigationEnd))
.subscribe((dogodekUsmerjanja: NavigationEnd) => {
const url = dogodekUsmerjanja.urlAfterRedirects;
this.urlNaslovi = [...this.urlNaslovi, url];
})
}
//filters last urls without the unwanted ones -> navigation back
public vrniPredhodnjeUrlNaslove(): string {
const dolzina = this.urlNaslovi.length;
return dolzina > 1 ? this.urlNaslovi[dolzina - 2] : '/';
}
//filters last urls without the unwanted ones -> navigation back
public vrniPredhodnjeUrlNasloveBrezIzbranih(): string {
const izloci: string[] = ['/registracija', '/prijava', '/obnoviGeslo','/vnesiNovoGeslo/:eposta',
'/uporabniki/:idUporabnika', ];
const filtrirano = this.urlNaslovi.filter(url => !izloci.includes(url));
const dolzina = filtrirano.length;
return dolzina > 1 ? filtrirano[dolzina - 1] : '/';
}
}
How to properly implement a redirecting service?