Issue
I'm getting error in the createBreadcrumbs function('Function lacks ending return statement and return type does not include 'undefined'.ts(2366)'). Please explain why i'm getting the error and how can i resolve it?
export class BreadcrumbComponent implements OnInit {
static readonly ROUTE_DATA_BREADCRUMB = 'breadcrumb';
readonly home = {icon: 'pi pi-home', url: 'home'};
menuItems!: MenuItem[];
constructor(private router: Router, private activatedRoute: ActivatedRoute) {}
ngOnInit(): void {
this.router.events
.pipe(filter(event => event instanceof NavigationEnd))
.subscribe(() => this.menuItems = this.createBreadcrumbs(this.activatedRoute.root));
}
private createBreadcrumbs(route: ActivatedRoute, url: string = '#', breadcrumbs: MenuItem[] = []): MenuItem[] {
const children: ActivatedRoute[] = route.children;
if (children.length === 0) {
return breadcrumbs
}
for (const child of children) {
const routeURL: string = child.snapshot.url.map(segment => segment.path).join('/');
if (routeURL !== '') {
url += `/${routeURL}`;
}
const label = child.snapshot.data[BreadcrumbComponent.ROUTE_DATA_BREADCRUMB];
if (label !== null || label !== undefined) {
breadcrumbs.push({label, url});
}
return this.createBreadcrumbs(child, url, breadcrumbs);
}
}
}
Solution
It seems that the Typescript's compiler does not understand that if the length of the array is different from zero, it will surely enter the loan and return a value.
So, the simple soultion is this:
private createBreadcrumbs(route: ActivatedRoute, url: string = '#', breadcrumbs: MenuItem[] = []): MenuItem[] {
const children: ActivatedRoute[] = route.children;
for (const child of children) {
const routeURL: string = child.snapshot.url.map(segment => segment.path).join('/');
if (routeURL !== '') {
url += `/${routeURL}`;
}
const label = child.snapshot.data[BreadcrumbComponent.ROUTE_DATA_BREADCRUMB];
if (label !== null || label !== undefined) {
breadcrumbs.push({label, url});
}
return this.createBreadcrumbs(child, url, breadcrumbs);
}
// if (children.length === 0)
return breadcrumbs;
}
Answered By - Shalom Peles
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.