我正在尝试验证响应电子邮件字段是否与登录用户的电子邮件匹配。当我导航到另一个用户设置但不属于当前登录用户的URL(detail /:id)时,Angular应显示一条错误消息。
到目前为止,一切都很好。但就我而言,显示正确响应的else函数没有执行。另外,console.log(appointmentDetails);
没有任何输出。
在反转if语句时,我已经测试了模板视图。这样就可以了。
更新:appointmentDetails = [0];
使我感到困惑。
有效的JSON响应:
{
id: 241772331,
firstName: "Justin",
lastName: "Miller",
email: "justin@miller.com", ...
}
错误JSON响应:
{
success: false,
message: 'You are not authorized to edit this apoointment.'
}
模板视图:
<div class="row show-hide-message" *ngIf="message">
<div [ngClass]="messageClass">
{{ message }}
</div>
</div>
<div class="box">
{{ appointmentDetails.type }}
{{ appointmentDetails.firstName }}
{{ appointmentDetails.lastName }}
</div>
AppointmentDetailComponent:
export class AppointmentDetailComponent implements OnInit {
username = '';
email = '';
message;
messageClass;
getData: any;
appointmentDetails = [0];
id: number;
private sub: any;
constructor(
private authService: AuthService,
private apiService: ApiService,
private route: ActivatedRoute
) {}
ngOnInit() {
this.sub = this.route.params.subscribe(params => {
this.id = +params['id']; // (+) converts string 'id' to a number
});
this.getData = this.getDataFunction;
this.getData();
}
getDataFunction() {
this.authService.getProfile().subscribe(profile => {
this.username = profile.user.username; // Set username
this.email = profile.user.email; // Set e-mail
if (profile.user.email) {
console.log(this.id);
this.apiService
.getAppointmentDetailsById(this.id, this.email)
.subscribe(appointmentDetails => {
if (!appointmentDetails.success) {
this.messageClass = 'alert alert-danger'; // Set error bootstrap class
this.message = appointmentDetails.message; // Set error message
} else {
console.log(appointmentDetails);
this.appointmentDetails = appointmentDetails;
}
});
}
});
}
ngOnDestroy() {
this.sub.unsubscribe();
}
}
服务器API路由:
const url = process.env.acuityUri + '/appointments/' + id;
fetch(url)
.then(response => response.json())
.then(json => {
if (json.email === user.email) {
res.json(json);
} else {
res.json({
success: false,
message: 'You are not authorized to edit this apoointment.'
});
}
});
答案 0 :(得分:1)
尝试以下方法,
this.apiService
.getAppointmentDetailsById(this.id, this.email)
.subscribe(appointmentDetails => {
console.log(appointmentDetails);
this.appointmentDetails = appointmentDetails;
}, (error) => {
this.messageClass = 'alert alert-danger'; // Set error bootstrap class
this.message = error.message;
});
答案 1 :(得分:1)
在成功和失败的场景中,您似乎只是返回两个不同的对象,而不会引发任何错误。因此,您必须在subscribe
本身的第一块中进行检查。无需使用error
块。因此,请寻找property
作为条件
所以,使用
this.apiService
.getAppointmentDetailsById(this.id, this.email)
.subscribe(appointmentDetails => {
if (appointmentDetails.hasOwnProperty('success') {
this.messageClass = 'alert alert-danger'; // Set error bootstrap class
this.message = appointmentDetails.message; // Set error message
} else {
console.log(appointmentDetails);
this.appointmentDetails = appointmentDetails;
}
});