angular - Angular 6 如何获取从组件到服务的方法调用状态?
问题描述
我想在我的组件中获取方法的状态。
SendEmail.component.ts
sendEmail(form: NgForm) {
this.contractService.sendEmail(form.value.FullName, form.value.content, form.value.Email);
// if successfull then show alert///
console.log(value);
form.resetForm(); }
我的服务.ts
sendEmail(FullName: string, content: string, Email: string) {
const Contact: Contacts = { _id: null, FullName: FullName, Content: content, Email: Email };
this.http
.post<{ message: string; contact: string }>('http://localhost:3000/api/contacts', Contact)
.pipe(
map( (data: any) => {
const result: any = [];
data.map(item => {
item = JSON.parse('Success');
});
return result;
})
)
.subscribe(responseData => {
this.contacts.push(Contact);
this.contactsUpdated.next([...this.contacts]);
});
}
我想在 sendEmail 方法内部成功或错误时获取组件中的状态。谢谢大家,加油
解决方案
好吧,您可以从sendEmail
方法中发送它。所以在那里而不是在subscribe
块中写你的逻辑,只需将它写在map
运算符中并sucess
从那里返回:
export interface Message {
message: string;
contact: string;
}
...
sendEmail(FullName: string, content: string, Email: string) {
const Contact: Contacts = {
_id: null,
FullName,
Content: content,
Email
};
return this.http.post<Message>('http://localhost:3000/api/contacts', Contact)
.pipe(
map((data: any) => {
const result: any = [];
data.map(item => {
item = JSON.parse('Success');
// this looks shady as you haven't returned anything from here
});
this.contacts.push(Contact); // Not sure what's Contact here
this.contactsUpdated.next([...this.contacts]); // Not sure what's contacts here.
return 'success';
})
);
}
然后,您可以返回subscribe
任何sendEmail
方法返回,这基本上是Observable<string>
:
sendEmail(form: NgForm) {
const { FullName, content, Email } = form.value;
this.contractService.sendEmail(FullName, content, Email)
.subscribe(res => {
if(res === 'success') alert('Got the response');
console.log(value);
form.resetForm();
})
}
注意:请务必仔细阅读评论。您在运算符中的逻辑map
看起来是错误的。不太清楚你在里面做什么。
推荐阅读
- php - Laravel Carbon,如何获取两个日期范围之间的所有日期?
- azure - 如何在身份验证和授权配置中添加范围
- python - BS4 仅打印网页的某些部分的问题
- javascript - 如何用一行代码过滤和修改对象数组?
- javascript - 无法在 Vuejs 中获得猫鼬查询的响应,但可以使用邮递员请求
- amazon-web-services - 在未知终止失败后从 EMR 节点检索日志文件?
- java - Java transferTo(out) 在每个字符之后而不是在按 Enter 之后回复
- javascript - Leaflet中具有高亮特征的多边形
- vuejs2 - 默认在延迟加载模式下扩展元素 UI 树 - Vue
- r - 如何在同一字符串中使用值和“文本”进行注释:ggplot2