1

there in my ProductGender enum -

enum ProductGender {
    Men,
    Women,
}

my getProducts service -

  public getProducts(
    gender: ProductGender,
    category: ProductCategory
  ): Observable<IProductInterface[]> {
    return this.httpProductService.getProducts(gender, category).pipe(
      catchError((errorResponse: HttpErrorResponse) => {
        let errorMessage: string;

        switch (errorResponse.status) {
          case 400:
            errorMessage = 'Getting products failed';
            break;
          default:
            errorMessage = 'An error occurred';
        }

        return throwError(errorMessage);
      }),
      map((response: IGetProductsResponse) => response.data!)
    );
  }

my get products resolver -

class ProductsResolver
  implements
    Resolve<
      Pick<IProductInterface, 'image' | 'title' | 'price' | 'description'>[]
    >
{
  constructor(private productService: ProductService) {}

  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<Pick<
  IProductInterface, 'image' | 'title' | 'price' | 'description'>[]
  > {
    return this.productService.getProducts(
      route.paramMap.get('gender'), - error is here
      route.paramMap.get('category')
    );
  }
}

i get the error on - route.paramMap.get('gender') i would like to know how can i assing that to be the enum type. thanks!

1 Answers1

0

2 problems:

  • If you don't specify what your enum values equal to (i.e. Men = 'Men'), then they're assigned numbers. You could parseInt your parameter, but you should validate it to be a proper enum value anyway.
  • Even if your enum values mapped to strings, you can't assign string | null to string since the value could be null and null cannot be assigned to string. And route.paramMap.get('gender') can return null if the parameter is missing. You should validate that anyway.

For the second problem, if you're 100% sure that the parameter will be present, use route.paramMap.get('gender')!. The ! tells TypeScript "I'm sure this is not null or undefined".

danday74
  • 52,471
  • 49
  • 232
  • 283
Kelvin Schoofs
  • 8,323
  • 1
  • 12
  • 31