首页 > 解决方案 > 具有 REST 服务的 Angular 资源:Web 应用程序和电子

问题描述

我们考虑将我们现有的 Angular Web 应用程序打包到一个电子项目中,以便离线运行。到目前为止,Web 应用程序通过 REST 请求加载配置。在电子应用程序中,此信息应位于本地文件中。

有什么建议可以有效地做到这一点吗?

我的第一个想法,在电子的快速服务器中模拟后端似乎并不常见。但是以角度重定向所有 REST 请求对我来说似乎也不是很直接。

标签: angularelectron

解决方案


所以我要做的是创建一个 Http 扩展类,并根据您通过 http 请求发送的参数更新端点。

Http扩展器:

export function HttpAuthCreator(http: HttpClient) {
return new HttpAuth(http)
}

@Injectable()
export class HttpAuth {
// Extending the HttpClient through the Angular DI.
public constructor(public http: HttpClient) {
// If you don't want to use the extended versions in some cases you can access 
the public property and use the original one.
// for ex. this.httpClient.http.get(...)
}

/**
 * GET request
 * @param string endPoint it doesn't need / in front of the end point
 * @param IRequestOptions options options of the request like headers, body, etc.
 * @returns Observable<T>
*/
public get<T>(endPoint: string, destination?: string, options?: IRequestOptions): Observable<T> {
return this.http.get<T>(
  this.updateEndpoint(endPoint, destination),
  this.configRequestOptions(options, destination)
)
}

然后你的子程序更新端点

private updateEndpoint(endpoint: string, destination?: string) {
if (destination === 'local') {
  return `${environment.localAPI}${endpoint}`
} else {
  return `${environment.onlineAPI}${endpoint}`
}
}

这样您就可以动态处理端点位置

  get() {
return this.http.get(`/organizations/${params.id}`, 'local').toPromise()
}

推荐阅读