简体   繁体   English

Angular2:为什么“其他”没有在订阅功能中执行?

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

I'm trying to verify that the response email field matches the email to the user which is logged-in.我正在尝试验证响应电子邮件字段是否与登录用户的电子邮件匹配。 When I navigate to an URL (detail/:id) which was set up by another user and doesn't belong to the currently logged-in user, Angular should display an error message.当我导航到由另一个用户设置且不属于当前登录用户的 URL (detail/:id) 时,Angular 应该显示一条错误消息。

So far so good.到现在为止还挺好。 But in my case, the else function, to display the correct response does not get executed.但在我的例子中,显示正确响应的 else 函数不会被执行。 Also console.log(appointmentDetails);还有console.log(appointmentDetails); doesn't give me any output.没有给我任何输出。

I already tested the template view as I inverted the if-statement.我已经在反转 if 语句时测试了模板视图。 So this would work.所以这会奏效。

UPDATE : The appointmentDetails = [0];更新appointmentDetails = [0]; makes me confused.让我很困惑。

Valid JSON response:有效的 JSON 响应:

{
  id: 241772331,
  firstName: "Justin",
  lastName: "Miller",
  email: "justin@miller.com", ...
} 

Error JSON response:错误 JSON 响应:

{
  success: false,
  message: 'You are not authorized to edit this apoointment.'
}

Template view:模板视图:

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

Server API route:服务器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.'
        });
      }
    });

It seems you are just returning two different objects in the success and failure scenarios and not throwing any error.似乎您只是在成功和失败场景中返回两个不同的对象,而没有抛出任何错误。 So you must do the check in the first block of subscribe itself.因此,您必须在subscribe本身的第一个块中进行检查。 No need to have the error block.不需要有error块。 So look for the property as a condition所以找property作为条件

So, use所以,使用

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

Try the following way,试试下面的方法,

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM