我有一些来自 REST API 的 Angular 服务数据
信息服务.ts
getCustomerDetails() {
this.http.get(this.localUrl + this.customerUrl + this.options).pipe(map((response: Response) => response.json()))
}
我的主页.ts
getData(){
this.infoServices.getCustomerDetails().subscribe(data=>{
if(data) {
this.name = data[0].customerInfo.name;
}
})
}
还有我的 home.html
<input type="text" value="{{this.name}}" formControlName="name" />
我的问题是有没有更好的方法来获取数据而不是做数据[0]?
端点:
router.post("/request/customer", (req, res) => {
var pendingRequest = new Customer({
name: req.body.name,
age: req.body.age,
isNewCustomer: true,
requestInfo: {
customerType: req.body.customerType,
sendTo: {
email: req.body.sendTo_email,
company: req.body.sendTo_company
},
returnTo: {
email: req.body.returnTo_email,
company: req.body.returnTo_company
}
},
});
pendingRequest
.save()
.then(result => {
console.log(result);
res.status(200).json({
message: "Handling POST request to /pending",
createdRequest: result
});
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
最佳答案
你可以在你的服务中使用 map 函数来完成它:
this.http.get(url).pipe(map((response: Response) => response[0])
这样当您订阅您的 observabla 时,检索到的日期将直接可用
您还想创建一个接口(interface)来定义您的响应结构,以便您可以轻松地操作您的对象
关于Angular 6 可观察和订阅,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54827053/