1
目前,我在我的用戶存儲一個對象數組,其中包含他投的所有選票。
這裏是模型:
voteOn(poll: Poll, userID: string, choice: number) {
UserModel.findById(userID, function (err, user) {
user.votes.push({poll, choice });
const body = JSON.stringify(user);
const headers = new Headers({'Content-Type': 'application/json'});
const token = localStorage.getItem('token')
? '?token=' + localStorage.getItem('token')
: '';
return this.http.patch('https://voting-app-10.herokuapp.com/user'+token, body, {headers: headers})
.map((response: Response) => response.json())
.catch((error: Response) => {
this.errorService.handleError(error);
return Observable.throw(error);
})
.subscribe();
});
}
這種方法節省了民意調查的用戶投票和選擇:
var schema = new Schema({
firstName: {type: String, required: true},
lastName: {type: String, required: true},
password: {type: String, required: true},
email: {type: String, required: true, unique: true},
polls: [{type: Schema.Types.ObjectId, ref: 'Poll'}]
votes: [{
poll: {type: Schema.Types.ObjectId, ref: 'Poll'},
choice: {type: number}
}]
});
當用戶選擇一個選項,這個方法是我服務的內部觸發他在用戶的投票數組內進行。
我的問題是這樣的:
問題:
當投票負荷,我想顯示在該用戶已經投票具有的選擇,他的民意調查做出預選並防止他不止一次投票。
我該如何做到這一點?
這裏是我的服務裏面的方法,獲得投票:
getPolls() {
return this.http.get('https://voting-app-10.herokuapp.com/poll')
.map((response: Response) => {
const polls = response.json().obj;
let transformedPolls: Poll[] = [];
polls.reverse();
for (let poll of polls) {
transformedPolls.push(new Poll(
poll.title,
poll.choice1,
poll.choice2,
poll.counter1,
poll.counter2,
poll.user.firstName,
poll._id,
poll.user._id,
)
);
}
this.polls = transformedPolls;
return transformedPolls;
})
.catch((error: Response) => {
this.errorService.handleError(error);
return Observable.throw(error);
});
}
這裏是一個民意調查component.html:
<article class="panel panel-default">
<div class="panel-body">
{{ poll.title }}
<br>
<br>
<form #form="ngForm">
{{ poll.counter1 }} votes <input type="radio" id="{{ poll.choice1 }}" name="my_radio" value="{{ poll.choice1 }}" (click)="onChoice1(form)"> {{ poll.choice1 }}
<br>
{{ poll.counter2 }} votes <input type="radio" id="{{ poll.choice2 }}" name="my_radio" value="{{ poll.choice2 }}" (click)="onChoice2(form)"> {{ poll.choice2 }}
</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>