Angular2:为什么 'else' 没有在订阅函数中执行?

Angular2: Why does 'else' not get executed in subscribe function?

我正在尝试验证回复电子邮件字段是否与发送给已登录用户的电子邮件相匹配。当我导航到由另一个用户设置且不属于当前登录用户的 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.'
        });
      }
    });

试试下面的方法,

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;
  });

看来你只是在成功和失败的场景中返回了两个不同的对象,并没有抛出任何错误。所以你必须在 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;
    }
  });