如何在新的BrowserWindow(Electron)中加载Angular 2+路径?

时间:2018-01-17 19:14:16

标签: angular electron

所以我有一个完整的Angular 5应用程序,我想转换成Electron应用程序。除了一件事,我已经在应用程序中完成了所有工作,就像在Web App表单中一样。我不能为我的生活弄清楚如何将路由加载到新的BrowserWindow。以下是我正在使用的内容以及到目前为止我尝试过的内容:

我用这个加载mainWindow:

mainWindow.loadURL(url.format({
    pathname: path.join(__dirname, 'dist/index.html'),
    protocol: 'file:',
    slashes: true
  }));

我通过mainWindow中的routerLink成功导航到Contact并获得此结果:

console.log(mainWindow.webContents.getURL()); = file:///C:/Me/Project/dist/contact

现在我不想导航到mainWindow内部的Contact,而是希望通过mainWindow在secondWindow中打开Contact页面:

的index.html:

<base href="./">

app.routes.ts:

export const routes: Routes = [{
    path: 'contact', data: { sectionTitle: 'Contact' },
    loadChildren: 'contact/contact.module#ContactModule'
}]

@NgModule({
  imports: [
    RouterModule.forRoot(routes, { useHash: false })
  ],
  exports: [RouterModule],
  declarations: [],
  providers: [],
})
export class AppRoutingModule { }

main.js:

secondWindow = new BrowserWindow({
    parent: mainWindow,
    width: 1024,
    height: 768,
    frame: false,
    minWidth: 1024,
    minHeight: 768,
    show: false
  });

secondWindow.loadURL('file://' + __dirname + 'dist/contact');
secondWindow.show();

这会产生以下错误消息:

Not allowed to load local resource: file:///C:/Me/Project/dist/contact

我试过没有运气(试过哈希路线以及使用哈希:真):

secondWindow.loadURL('file://' + __dirname + '/dist/contact');
secondWindow.loadURL('file:' + __dirname + '/dist/contact');
secondWindow.loadURL('file:' + __dirname + 'dist/contact');
secondWindow.loadURL('file:' + __dirname + 'dist/index.html#/contact');

有什么想法吗?这是阻止发布这款Electron应用程序的唯一因素。

2 个答案:

答案 0 :(得分:4)

如果没有看到你的代码和Angular设置,那么知道它为什么不起作用是很棘手的。但是,您应该使用node.js urlconst path = require('path'); const url = require('url'); window.loadURL(url.format({ pathname: path.join(__dirname, './index.html'), protocol: 'file:', slashes: true, hash: '/contact' })); 模块来构建您的网址。

猜测一下,我会说你需要加载你的基本html文件,哈希应该是你想要加载的路径:

file:///full-path/to-your/app-root/index.html#/contact"

这会产生类似的结果:

secondWindow.loadURL('file:' + __dirname + 'dist/index.html#/contact');

这意味着您的最后一个示例是最接近的,但手动构建网址意味着它无效:

  

<time datetime="...">

答案 1 :(得分:1)

除了当前接受的答案外,我还需要打开useHash中的AppRoutingModule

@NgModule({
  imports: [RouterModule.forRoot(routes, { useHash: true })],
  exports: [RouterModule]
})