Reputation: 4539
I have this simple class :
import {Router} from '@angular/router';
export class NotLogged {
constructor(error, private router: Router) {
alert('Not logged in !');
this.router.navigate(['/']);
}
}
And then I'm trying to call it from a service :
if(error.status === 401)
return Observable.throw(new NotLogged(error.json()));
Of course I get an error Supplied parameters do not match any signature of call target
. How can I do that ?
Thanks ahead.
Upvotes: 1
Views: 77
Reputation: 222309
The class doesn't inherit from another one and isn't supposed to have super
. If it is supposed to be Error
subclass, router
instance should be passed from a service where the class is instantiated:
new NotLogged(error.json(), router)
Usually classes that are supposed to make use of Angular DI shouldn't be constructed manually. In this case it can be existing class instance that will be used in the application, not a class itself. Also, a promise that router.navigate
returns is valuable and shouldn't be discarded:
@Injectable()
export class NotLogged {
constructor(private router: Router) {}
notLogged(error) {
alert('Not logged in !');
return this.router.navigate(['/']);
}
}
At this point it becomes obvious that class design went wrong, and notLogged
should belong to not to just some class but to a service that does something besides logging out, e.g. Auth
.
Upvotes: 1
Reputation: 463
I'm not clear why you call super();
in a nonderived class. For the question, you should use a different method to get the object from your class.
export class NotLogged {
constructor(private router: Router) {
}
proceedWithError(error:any){
alert('Not logged in !');
this.router.navigate(['/']);
return this;
}
}
then you can use that method to do the needful.
if(error.status === 401)
return Observable.throw(new NotLogged().proceedWithError(error.json());
Upvotes: 1
Reputation: 707
I'd add router as a dependency to the service and inject it manually.
But the usage of your class is a bit strange, why would you redirect in the constructor of a data/error class. Maybe the better solution is to remove the router from the class and check for this error class in the consumer of the service (probably a component) and redirect when needed. This also helps with separating your view logic (redirecting) from your business logic
Upvotes: 1
Reputation: 15292
constructor should be,
constructor(private error : any, private router: Router) {
Upvotes: 1