Javascript 如何将数据从Angular传输到Node.js?

Javascript 如何将数据从Angular传输到Node.js?,javascript,node.js,angular,typescript,Javascript,Node.js,Angular,Typescript,我想在我的Angular应用程序中创建一个评论部分。这些注释应该存储在数据库中,所以我想将数据从Angular转发到Node.js,在那里可以传递到数据库。因此,我在detail.component.html中为注释创建了一个输入字段。当用户点击enter键时,将保存注释 {{value}} 在detail.component.ts中,我将注释保存在变量中: public value: any= [] update(comment: any) { this.value = comment;

我想在我的Angular应用程序中创建一个评论部分。这些注释应该存储在数据库中,所以我想将数据从Angular转发到Node.js,在那里可以传递到数据库。因此,我在detail.component.html中为注释创建了一个输入字段。当用户点击enter键时,将保存注释


{{value}}

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

public value: any= []
update(comment: any) { this.value = comment; }
//code
this.dataService.addComment().subscribe(comment => this.value = comment)
这里是第一个问题-如何将注释获取到data.service.ts

还有一个实际的问题:如何将此评论转发到node.js应用程序中的server.js

我是个新手,所以我对如何做到这一点一无所知。我发现这个问题同样有用,但无法应用到我的用例中。那么,如何将数据从Angular传输到Node.js

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

正如您在问题中所述,您正在将注释保存到变量
。将值变量传递给服务:

this.dataService.addComment(this.value).subscribe(res => {
  // check fo response, and maybe chain errors
});
然后是一个实际的问题:我怎样才能转发这个评论 是否在node.js应用程序中连接到server.js

在数据服务中:

constructor(private http: HttpClient) {
}

addComment(comment) {
  return this.http.post<any>('server-url-route', comment);
}
构造函数(私有http:HttpClient){
}
添加注释(注释){
返回此.http.post('server-url-route',comment);
}
在节点Js中:


有一个添加注释的路径和一个将注释保存到数据库的函数。

如果您已经在服务器端定义了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
      )
  }

您的post api是否在服务器端(nodejs)实现?@SiddharthPal-是的,api是由server.js(nodejs)创建的。我收到以下错误消息:属性“subscribe”在类型“void”上不存在。对于“subscribe”在“detail.component.ts”中的“subscribe”,我很抱歉,我忘了返回可观察的。更新了我的答案。请检查console.log中的now,我会收到以下错误消息:“myhostname/api/comments 404(Not Found)”(“cannot POST”)-我是否必须以某种方式创建此页面才能在那里发布内容?我在server.js的Node.js中有类似“app.get('/api/comments',function,req,res,next){/*code*/}我不确定你是否应该首先从postman或其他客户机检查你的api。你说你可以从api获取数据,所以我假设你的代理设置是正确的。gotcha在你的服务器端,api应该是POST动词not get。
app.POST('/api/comments',function,req,res,next){/*code*/}
我收到此错误消息:类型“void”上不存在属性“subscribe”。对于detail.component.ts“@butterfly中的“subscribe”,您必须在数据服务中使用
addComment(comment){返回this.http.post('server-url-route',comment);}
。在console.log中,我收到此错误消息:“myhostname/api/comments 404(未找到)”(“无法发布”)-我必须创建此页面才能在那里发布内容吗?我在server.js的Node.js中有类似“app.get('/api/comments',function,req,res,next){/*code*/}
  addComment(title: string) {
    const postData = new FormData();
    postData.append('title', title);
    return this.http
      .post<{ title: string; }>(
        '<HOST_NAME>/api/comments',
        postData
      )
  }
this.dataService.addComment(this.value).subscribe(console.log);