Reputation: 723
I have an object of type "user" that should have a function "getPermission()". During runtime (of Angular 7) it throws the error "TypeError: this.user.getPermission is not a function".
Here ist what seems to me to be the essential context:
My user class:
export class User {
...
public getPermission(): boolean {
return true;
}
...
}
I have a service from which I fetch a user from the api (which is asp.net core):
getUser(id): Observable<User> {
return this.http.get<User>(this.baseurl + 'user/' + id);
}
then I have a resolver:
@Injectable()
export class UserEditResolver implements Resolve<User> {
constructor(private userService: UserService, private authService: AuthService,
private router: Router,
private alertify: AlertifyService) {}
resolve(route: ActivatedRouteSnapshot): Observable<User> {
return this.userService.getUser(this.authService.decodedToken.nameid).pipe(
catchError(error => {
this.alertify.error('Problem retrieving your data');
this.router.navigate(['/users']);
return of(null);
})
);
}
}
and finally in my component I call the function getPermission:
user: User;
ngOnInit() {
this.route.data.subscribe(data => {
this.user = data['user'];
});
const t: boolean = this.user.getPermission();
}
And as written above, I get the error:
TypeError: this.user.getPermission is not a function
Beside the function and all other functions which are not present at runtime, all properties loaded from the api are there.
I would be so thankful for any hit how this could happen !
Upvotes: 1
Views: 231
Reputation: 15599
TypeScript only exists in compile time. It does not do anything in runtime.
Simply doing this.http.get<User>(...)
will not convert anything you received to the class User
you specify.
You need to parse the input yourself and instantiates the User
instance.
Upvotes: 3
Reputation: 41445
create an instance of the class
user: User = new User();
Upvotes: 0