【问题标题】:How to transfer data from Angular to Node.js?如何将数据从 Angular 传输到 Node.js?
【发布时间】:2020-04-10 02:34:58
【问题描述】:

我想在我的 Angular 应用程序中构建一个评论部分。这些 cmets 应该存储在数据库中,所以我想将数据从 Angular 转发到 Node.js,然后可以将其传递到数据库。所以我在 detail.component.html 中为 cmets 创建了一个输入字段。当用户点击回车时,评论被保存。

<input #box (keyup.enter)="update(box.value)">
<p>{{value}}</p>

detail.component.ts 我将注释保存在一个变量中:

public value: any= []
update(comment: any) { this.value = comment; }
//code
this.dataService.addComment().subscribe(comment => this.value = comment)

这是第一个问题 - 我如何获得对 data.service.ts 的评论?

//code
addComment() {}

然后是实际的问题:如何在 node.js 应用程序中将此评论转发到 server.js?

我对 Angular 很陌生,所以我对如何实现这一点一无所知。我发现这个问题How to pass form data from angular to nodejssamewhat 很有用,但无法将其应用于我的用例。那么如何将数据从 Angular 传输到 Node.js?

【问题讨论】:

  • 你的post api是在服务器端(nodejs)实现的吗?
  • @SiddharthPal - 是的,API 是由 server.js (nodejs) 创建的

标签: javascript node.js angular typescript


【解决方案1】:

如果您已经在服务器端定义了 API(POST),那么您只需调用http.post 方法,如下所示:

  addComment(title: string) {
    const postData = new FormData();
    postData.append('title', title);
    return this.http
      .post<{ title: string; }>(
        '<HOST_NAME>/api/comments',
        postData
      )
  }

要使用它,您必须订阅它,因为 Observables 是惰性的,如下所示:

this.dataService.addComment(this.value).subscribe(console.log); 

【讨论】:

  • 我收到此错误消息:“void”类型上不存在属性“subscribe”。对于“detail.component.ts”中的“subscribe”
  • 对不起,我忘了返回 Observable..更新了我的答案。请立即查看
  • 在 console.log 中我收到此错误消息:“myhostname/api/cmets 404(未找到)”(“无法发布”) - 我是否必须以某种方式创建此页面才能发布有什么东西吗?我在 server.js 中的 Node.js 中有类似“app.get('/api/cmets', function, req, res, next) {/*code*/}
  • 我不确定你应该先从邮递员或其他客户那里检查你的 api。您说您可以从 api 获取数据,所以我认为您的代理设置是正确的。
  • 在你的服务器端,api应该是POST动词而不是GET。 app.post('/api/comments', function, req, res, next) {/*code*/}
【解决方案2】:

这是第一个问题 - 我如何获得评论 data.service.ts?

正如您在问题中所说,您将评论保存到变量value。将值变量传递给服务:

this.dataService.addComment(this.value).subscribe(res => {
  // check fo response, and maybe chain errors
});

然后是实际的问题:我如何转发此评论 到node.js App中的server.js?

在数据服务中:

constructor(private http: HttpClient) {
}

addComment(comment) {
  return this.http.post<any>('server-url-route', comment);
}

在 Node Js 中:

具有添加评论的路径和将评论保存到数据库的功能。

【讨论】:

  • 我收到此错误消息:“void”类型上不存在属性“subscribe”。对于“detail.component.ts”中的“subscribe”
  • @butterfly 你必须在数据服务中使用addComment(comment) { return this.http.post&lt;any&gt;('server-url-route', comment); }
  • 在 console.log 中我收到此错误消息:“myhostname/api/cmets 404(未找到)”(“无法发布”) - 我是否必须以某种方式创建此页面才能发布有什么东西吗?我在 server.js 中的 Node.js 中有类似“app.get('/api/cmets', function, req, res, next) {/*code*/}
猜你喜欢
  • 2019-02-05
  • 2018-01-13
  • 2022-12-12
  • 1970-01-01
  • 1970-01-01
  • 2020-05-31
  • 2015-10-15
  • 2017-07-20
  • 2017-02-05
相关资源
最近更新 更多