5

我想动态创建一个 URL 树并在 Angular 的路由器中使用它而不是“魔术”字符串。我有这些课程:

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();

所以我可以使用导航到个人资料

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

并在路由器模块中注册为

path: urlTree.user.profile.segmentUrl

但是用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

我怎样才能让它工作?或者也许有人知道一个更好的解决方案来避免项目中的“神奇” URL 和段?

4

0 回答 0