Reputation: 1408
Using Angular 6.1 and RxJs 6, I'm trying to implement a resolver for a component on an individual user.
My userService
http call is this:
getUserById(id: string): Observable<AppUser> {
return this.http.get<AppUser>(this.baseURL + id, httpOptions);
}
And my resolver:
import { Injectable } from "@angular/core";
import { Resolve, Router, ActivatedRouteSnapshot } from "@angular/router";
import { AppUser } from "../models/User/IAppUser";
import { UserService } from "../services/users/user.service";
import { AlertifyService } from "../../coreModule/alertify/alertify.service";
import { Observable, of } from "rxjs";
import { catchError } from "rxjs/operators";
@Injectable()
export class UserDetailResolver implements Resolve<AppUser> {
constructor(
private userService: UserService,
private router: Router,
private alertify: AlertifyService
) { }
resolve(route: ActivatedRouteSnapshot): Observable<AppUser> {
return this.userService.getUserById(route.params['id'])
.pipe(
catchError(error => {
this.alertify.error('Problem retrieving data');
this.router.navigate(['/home']);
return of(null)
})
);
}
But because I'm trying to return null instead of an AppUser
typescript is throwing an error. Not sure what I'm doing wrong since I thought rxjs of
was supposed to handle this.
Upvotes: 0
Views: 104
Reputation: 5364
I might be missing something, but you have a method that is declared to return a stream of AppUser
, which implements interface Resolve<AppUser>
. And with catchError
+ of(null)
that method is effectively returning a stream of either null
or AppUser
. As the TS compiler is rightfully complaining about.
To fix this you may either return an EMPTY
observable. It emits no values and immediately completes. NEVER
is another constant observable that will never emit and never complete. Pick the one you need. E.g.
catchError(()=>{
// ...
return EMPTY;
})
NOTE: with this approach you might need to do type casting, e.g. EMPTY as Observable<AppUser>
. Though it will be an honest casting — as empty observable can be of any type of observable.
Or if you do need to emit a null
value on the stream — declare the method as returning Observable<AppUser | null>
, which is the actual type that it currently returns. And you'll have to also update the Resolve<AppUser>
to Resolve<AppUser | null>
.
==
TO EMPHASIZE THIS:
In most cases you don't want to lie to your typing system and force cast a Observable<null | AppUser>
type to a Observable<AppUser>
.
==
Hope it helps
Upvotes: 0