5

I want to dynamically create a URL tree and use it in Angular's router instead of "magic" strings. I have these classes:

export abstract class UrlNode {
    protected parentUrl?: string;
    protected abstract shortUrl: string;

    constructor(parent: UrlNode) {
        this.parentUrl = parent && parent.path;
    }

    public get segmentUrl(): string {
        return this.shortUrl;
    }

    public get path(): string {
        if (!this.parentUrl) {
            return this.shortUrl;
        }

        if (!this.shortUrl) {
            return this.parentUrl;
        }

        return `${this.parentUrl}/${this.shortUrl}`;
    }
}

export class Profile extends UrlNode {
    protected shortUrl = "profile";
}

export class User extends UrlNode {
    public readonly profile: Profile;
    public readonly someSubroute: SomeSubroute;

    protected shortUrl = "user";

    constructor(parent: UrlNode) {
        super(parent);

        this.profile = new Profile(this);
        this.someSubroute = new SomeSubroute(this);
    }
}

export class AppTree {
    public readonly user: User;
    public readonly someRoute: SomeRoute;

    constructor() {
        this.user = new User(this);
        this.someRoute = new SomeRoute(this);
    }
}

export const urlTree = new AppTree();

So I can navigate to profile using

router.navigateByUrl(urlTree.user.profile.path) 

and register it in router module as

path: urlTree.user.profile.segmentUrl

But there is an error when compile with AOT.

ERROR in Error: Error encountered resolving symbol values statically. Calling function 'AppTree', function calls are not supported. Consider replacing the function or lambda with a reference to an exported function, resolving symbol urlTree in routes/url-tree.model.ts, resolving symbol urlTree in routes/index.ts, resolving symbol urlTree in index.ts, resolving symbol app-routing.module.ts, resolving symbol AppRoutingModule in app-routing.module.ts, resolving symbol AppRoutingModule in app-routing.module.ts

How can I make it work? Or maybe somebody knows a better solution to avoid "magic" URLs and segments in the project?

E. Efimov
  • 443
  • 1
  • 5
  • 10

0 Answers0