【发布时间】:2021-07-03 16:52:22
【问题描述】:
我在 Node.js 中创建了一个名为GetFileNames() 的函数,该函数返回一个字符串数组。
现在我想在我的 TS 脚本中调用它并用它来填充本地数组。
问题是我不知道如何调用这个函数。有人可以帮帮我吗?
【问题讨论】:
标签: node.js angular typescript
我在 Node.js 中创建了一个名为GetFileNames() 的函数,该函数返回一个字符串数组。
现在我想在我的 TS 脚本中调用它并用它来填充本地数组。
问题是我不知道如何调用这个函数。有人可以帮帮我吗?
【问题讨论】:
标签: node.js angular typescript
您需要一个中间件,例如 express 并从您的 .ts 文件调用服务(通过 ng generate service someservice 生成),然后向您的节点路由发出请求,这里有一个小例子来说明我的意思:
somecomponent.ts:
import { someService } from 'src/app/services/someservice.service';
...
..
files = []
/* INFO: Function for getting all files */
getAllFiles() {
this.someservice.getAllFiles().subscribe((res) => {
if (!res.success) {
this.files = [];
}
else {
this.files = res.data;
}
});
}
someservice.service.ts:
import { Injectable } from '@angular/core';
import { environment } from '../../environments/environment';
import * as rxjs from 'rxjs';
import { HttpHeaders, HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class someService {
....
...
..
// INFO: Function to create headers, add token, to be used in HTTP requests
createAuthenticationHeaders() {
this.loadToken(); // INFO: Get token so it can be attached to headers
// INFO: Headers configuration options
this.options = new HttpHeaders({
'Content-Type': 'application/json',
'authorization': this.authToken
});
}
/* INFO: service for getting files from filesystem */
getAllFiles() {
this.createAuthenticationHeaders();
if (environment.production == true || environment.marker == true) {
let apiURL = '/someroute/getAllFiles';
return this.httpClient.get<any>(apiURL, { headers: this.options });
}
else {
let apiURL = `http://localhost:${environment.port}/someroute/getAllFiles`;
return this.httpClient.get<any>(apiURL, { headers: this.options });
}
}
}
someroute.js:
module.exports = (router) => {
router.get('/getAllFiles', (req, res) => {
filenames = fs.readdirSync(`some/path/to/files`);
res.json({ success: true, data: filenames });
});
return router;
}
显然这只是一个最小的示例,您需要自己处理错误处理等(例如,以防目录不存在)。前端和后端之间的身份验证相同。在您的 app.js 中,您需要 require 路由并通过 app.use('/someroute', someRoute);“使用”它
澄清来自 cmets 的问题的附件:
这是一个非常常见的技术栈(这里有一个额外的数据库):
这是一个常见项目架构的示例:
--projectroot
|___ app.js
|
|___ /client // your frontend app (i.E. Angular, React etc..)
| |
| |___ /node-modules // node-modules for frontend defined in package.json
| |___ /src
| |
| |___ /app // web-app with components, serives, assets etc
| |___/components
| |___/services
| |___/assets
|
|___ /node-modules // node-modules for backend defined in package.json
|
|___ /routes // route-files
【讨论】:
myservice-serivice/public/javascripts/myScript.js里面可以吗?在这种情况下,假设函数所在的脚本名称为 myScript.js。