【问题标题】:ERROR TypeError: Cannot read property 'poll' of undefined错误类型错误:无法读取未定义的属性“轮询”
【发布时间】:2017-10-21 04:53:22
【问题描述】:

情况:

我真的不知道是什么导致了这个错误。

但我知道它的起源。相关代码如下。

我做错了什么?

编辑:添加了路由器代码。如果您认为缺少任何相关内容,请告诉我。


错误:

core.es5.js?0445:1084 ERROR TypeError: Cannot read property 'poll' of undefined


代码:

服务

voteOn(poll: Poll, userID: string, choice: number) {
  var user;
  this.http.get('http://localhost:3000/user/'+userID)
  .map(response => response.json())
  .subscribe(
        json => {
          user = JSON.parse(json),
          console.log("USER :"+user);
          if (user.votes == undefined) {
            user.votes = [{poll, choice}];
          } else {
            user.votes.push({poll, choice});
          }
          const body = user;
          const headers = new Headers({'Content-Type': 'application/json'});
          const token = localStorage.getItem('token')
              ? '?token=' + localStorage.getItem('token')
              : '';
          return this.http.patch('http://localhost:3000/user/'+token, body, {headers: headers})
              .map((response: Response) => response.json())
              .catch((error: Response) => {
                  this.errorService.handleError(error);
                  return Observable.throw(error);
              })
              .subscribe();
        }
   )
}

poll.component.ts

import { Component, Input } from "@angular/core";

import { Poll } from "./poll.model";
import { PollService } from "./poll.service";

@Component({
    selector: 'app-poll',
    templateUrl: './poll.component.html',
    styles: [`
        .author {
            display: inline-block;
            font-style: italic;
            font-size: 12px;
            width: 80%;
        }
        .config {
            display: inline-block;
            text-align: right;
            font-size: 12px;
            width: 19%;
        }

        .panel {
            width: 600px;
            margin: auto;
            margin-top: 30px;
        }

        .panel-body {
            padding: 20px;
        }
    `]
})
export class PollComponent {
    @Input() poll: Poll;

    constructor(private pollService: PollService) {}

    votes: any;

    ngOnInit() {
        this.pollService.voted(this.poll, localStorage.getItem('userId')).subscribe(
            data => {
                console.log("DATA:" + data);
                this.votes = data.votes;
                console.log("NGONINIT this.votes: "+ this.votes);
            },
            err => { console.log("NGONINIT ERROR: "+ err) },
            () => { console.log("SUBSCRIBE COMPLETE this.votes: "+ this.votes); }
        );
    }

    onEdit() {
        this.pollService.editPoll(this.poll);
    }

    onDelete() {
        this.pollService.deletePoll(this.poll)
            .subscribe(
                result => console.log(result)
            );
    }

    onChoice1() {
      this.pollService.increaseCounter1(this.poll);
      this.onVote1();
    }

    onChoice2() {
      this.pollService.increaseCounter2(this.poll);
      this.onVote2();
    }

    onVote1() {
      this.pollService.voteOn(this.poll,  localStorage.getItem('userId'), 1);
    }

    onVote2() {
      this.pollService.voteOn(this.poll,  localStorage.getItem('userId'), 2);
    }

    belongsToUser() {
        return localStorage.getItem('userId') == this.poll.userId;
    }

    alreadyVotedFor(choice: number) {
      let result = "";
      if (this.votes) {
          console.log("THIS.VOTES: "+this.votes);
          for (var i = 0; i < this.votes.length; i ++) {
              if (this.votes[i].poll == this.poll.pollId) {
                  result = "disabled";
                  if (this.votes[i].choice == choice) {
                      result =  "selected";
                  }
              }
          }
      }
      return result;
    }

}

poll.component.html

<article class="panel panel-default">
    <div class="panel-body">
      {{ poll.title }}
      <br>
      <br>
      <form #form="ngForm">
        <fieldset [disabled]="alreadyVotedFor(-1)">
          {{ poll.counter1 }} votes <input type="radio" id="{{ poll.choice1 }}" name="my_radio" value="{{ poll.choice1 }}" (click)="onChoice1(form)" [checked]="alreadyVotedFor(1)">  {{ poll.choice1 }}
          <br>
          {{ poll.counter2 }} votes <input type="radio" id="{{ poll.choice2  }}" name="my_radio" value="{{ poll.choice2 }}" (click)="onChoice2(form)" [checked]="alreadyVotedFor(2)">  {{ poll.choice2 }}
        </fieldset>
      </form>

    </div>
    <footer class="panel-footer">
        <div class="author">
            {{ poll.username }}
        </div>
        <div class="config" *ngIf="belongsToUser()">
            <a (click)="onEdit()">Edit</a>
            <a (click)="onDelete()">Delete</a>
        </div>
    </footer>
</article>

user.model

import { Poll } from '../polls/poll.model';

export class User {
    constructor(public email: string,
                public password: string,
                public votes?: [{poll: Poll, choice : number }],
                public firstName?: string,
                public lastName?: string
                ) {}
}

路线/用户

router.patch('/', function (req, res, next) {
    var decoded = jwt.decode(req.query.token);
    User.findById(decoded.user._id, function (err, user) {
      user.votes = req.body.votes;
      user.save(function(err, result) {
          if (err) {
              return res.status(500).json({
                  title: 'An error occurred',
                  error: err
              });
          }
          res.status(201).json({
              poll: 'Vote Saved',
              obj: result
          });
      });
   });
});

【问题讨论】:

  • 您的 PATCH 请求在此之前有一个内部服务器错误。
  • @Pengyy 这是简写{ poll: poll, choice: choice }
  • @NeilLunn 哦,这是新功能吗?抱歉,我可能不知道。
  • @NeilLunn 确实,我认为这两个错误有些关联。以防万一您想知道:是的,这是我在控制台中遇到的仅有的 2 个错误。
  • 请重新阅读minimal reproducible example。关键是你删除一些东西,直到你有一个小的、独立的问题示例。这几乎不是一个小而独立的示例。

标签: javascript angular typescript


【解决方案1】:

您的代码没有完全显示问题。我能够使用上一个问题中的在线演示找出问题所在。

错误发生在ErrorService。更准确的

const errorData = new Error(error.title, error.error.poll);

【讨论】:

    猜你喜欢
    • 2018-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-03
    • 2021-11-22
    • 2018-07-12
    • 2021-12-16
    • 2020-08-16
    相关资源
    最近更新 更多