下面是一个使用Angular和Electron创建应用程序,并根据桌面或Web模式查询Web API或数据库的解决方案的代码示例:
首先,确保你已经安装了Angular和Electron。
创建一个新的Angular项目:
ng new my-app
cd my-app
npm install electron --save-dev
const { app, BrowserWindow } = require('electron');
const url = require('url');
const path = require('path');
let win;
function createWindow() {
win = new BrowserWindow({ width: 800, height: 600 });
if (process.env.NODE_ENV === 'development') {
win.loadURL('http://localhost:4200');
} else {
win.loadURL(
url.format({
pathname: path.join(__dirname, 'dist/index.html'),
protocol: 'file:',
slashes: true,
})
);
}
win.on('closed', () => {
win = null;
});
}
app.on('ready', createWindow);
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', () => {
if (win === null) {
createWindow();
}
});
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class ApiService {
constructor(private http: HttpClient) {}
getData(): Observable {
return this.http.get('https://api.example.com/data');
}
}
import { Component, OnInit } from '@angular/core';
import { ApiService } from './service';
@Component({
selector: 'app-root',
template: `
Data:
- {{ item }}
`,
})
export class AppComponent implements OnInit {
data: any;
constructor(private apiService: ApiService) {}
ngOnInit(): void {
this.apiService.getData().subscribe((data) => {
this.data = data;
});
}
}
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';
import { AppComponent } from './component';
import { ApiService } from './service';
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule, HttpClientModule],
providers: [ApiService],
bootstrap: [AppComponent],
})
export class AppModule {}
import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/module';
if (process.env.NODE_ENV === 'production') {
enableProdMode();
}
platformBrowserDynamic()
.bootstrapModule(AppModule)
.catch((err) => console.error(err));
"scripts": {
"electron": "electron .",
"start-electron": "ng serve & npm run electron",
"build-electron": "ng build --prod && ng run my-app:server:production && electron ."
},
"build": {
"builder": "@angular-devkit/build-angular:browser",
"options": {
"outputPath": "dist/my-app",
"index": "src/index.html",
"main": "src/electron.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "src/tsconfig.app.json",
"aot": true,
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"src/styles.css"
],
"scripts": []
},
"configurations": {
"production": {
"fileReplacements": [
{
"replace":