首页 > 解决方案 > Flask 使用客户端路由服务 Angular 应用程序

问题描述

我正在设置一个应用程序,它将有一个简单的 Flask 服务器,并使用 Typescript/Angular8 作为前端——我对 web 比较陌生,对 Angular 也很陌生。一般的方案是编译前端,然后让 Flask 从编译到的目录中提供文件。在编译前端时,我们在 angular.json 中有如下配置:

"options" {
  "outputPath": "dist/static",
  "deployUrl": "/static/",
  "baseHref": "/static/",
  ...

所以编译的 js/html/assets 被下推到一个静态文件夹。

我将画一个我正在处理的问题的最小示例:

假设烧瓶服务器定义了一个根端点:

@app.route("/")
def index():
    return send_from_directory(config.dist_dir, 'index.html')

提供主页(config.dist_dir该静态目录在哪里)。

现在假设我将路由添加到 Angular 前端,以便我的 app.component.html 只包含<router-outlet></router-outlet>并且主视图被推送到单独的组件(我在这里称其为“Blah”)。

有了这个设置,我就有了 app-routing.module.ts 的基本模板:

const routes: Routes = [
  { path: 'blah', component: BlahComponent }
  { path: '', component: BlahComponent }
];

Flask 正确地为正确显示的 index.html 提供服务BlahComponent但问题是它/static被添加到了 URL 中。在您从 url 中删除 static 之前,来自浏览器的后续请求将不起作用。

我目前的解决方法是包含以下类并将其用作 LocationStrategy:

export class TempPathLocationStrategy extends PathLocationStrategy {
  prepareExternalUrl(internal: string): string {
    return super.prepareExternalUrl(internal).substr('/static'.length);
  }
}

这暂时有效,但我觉得我必须遗漏一些东西——客户端路由或我遗漏的包信息的某种配置。

这种解决方法的一个问题是,现在您只能在服务器也运行时才能破解前端(ng serve希望从静态文件夹中提供服务,但如果您从 url 中删除它,则无法继续提供服务)。

标签: typescriptflaskangular8

解决方案


推荐阅读