将数据从Angular2组件发送到node.js
所以我想发送一些string
值到我的节点服务器,并在MySQL表中find该值。
我有一个从服务获取数据的组件
ngOnInit() { this.instructionsService.getAllInstructions().subscribe(instructions => { this.instructions = instructions; }); }
然后我有一个从node
服务器获取数据的服务
getAllInstructions() { return this.http.get('/api/profile/') .map(res => res.json()); }
最后我有节点api
app.get('/profile',getAllInstructions); function getAllInstructions(req,res){ connection.query("select * from users where id='somekindofid'",function(err, rows, fields) { res.json(rows); } }
`
我想用我的组件发送的值replace“somekindofid”
我怎样才能做到这一点?
您应该将id
传递给其URL本身内的节点方法。 对于相同的,你应该改变API路由到/profile/:id
其中id
是将从API的消费者传递的参数。
节点
app.get('/profile/:id',getAllInstructions); function getAllInstructions(req,res){ connection.query("select * from users where id="+ req.params.id,function(err, rows, fields) { res.json(rows); } }
服务
getAllInstructions(id) { return this.http.get(`/api/profile/${id}`) .map(res => res.json()); }
零件
ngOnInit() { let userId = 'pankaj'; this.instructionsService.getAllInstructions(userId).subscribe(instructions => { this.instructions = instructions; }); }