React use axios return Axios Error {message: 'Network Error'} and TypeError: Cannot read properties of undefined (reading 'path') - node.js

when I click submit button, then web and terminal will return error like me title
but i try postman is ok , so i think is my axios setting error,how can i fixed this error? I found many similar questions, but can't not help me
the other question is , my form tag action is "/addItems", but i sending request , i got this error CANNOT POST / addItems Post http://localhost:3000/addItems 404 (Not Found)
(axios setting )
post(id, title, description, price, avatar) {
let token;
if (localStorage.getItem("user")) {
token = JSON.parse(localStorage.getItem("user")).token;
} else {
token = "";
}
const formData = new FormData();
// formData.append("id", id);
// formData.append("title", title);
// formData.append("description", description);
// formData.append("price", price);
formData.append("avatar", avatar);
return axios.post(
API_URL + "/addItems",
{ formData },
{
headers: {
Authorization: token,
"Content-Type": "multipart/form-data"
}
}
);
}
(item.route)
itemRouter.post("/addItems", upload.single("avatar"), async (req, res) => {
let { id, title, description, price, avatar } = req.body;
if (req.user.isMember()) {
return res.status(400).send("Only admin can add new items");
}
console.log(req.file);
avatar = req.file.path;
const newItem = new Item({
id,
title,
description,
price,
avatar
});
try {
await newItem.save();
console.log(req.file);
res.status(200).send("New item has been saved.");
} catch (err) {
res.status(400).send("Error");
console.log(err);
}
});
(addItemsComponent)
const handleChangePost = () => {
if (currentUser.user.role !== "admin") {
window.alert("Member can't not post item!! ");
navigate("/");
} else {
ItemService.post(avatar)
.then(() => {
window.alert("Post successfully");
navigate("/");
})
.catch((error) => {
console.log(error);
console.log(error.response);
setErrorMessage(error.response.data);
});
}
};
return (
<div>
<form action="/addItems" method="post" enctype="multipart/form-data">
<input onChange={handleChangeAvatar} value={avatar} type="file" name="avatar" />
<button type="submit" onClick={handleChangePost}>
Submit
</button>
</form>
</div>
);

Try this
return axios.post(API_URL + "/addItems", formData,
{
headers: {
Authorization: token,
"Content-Type": "multipart/form-data"
}
}
);

Related

How to create a comment and reply section with MERN STACK

I created a comment session on my entertainment website
It’s working on backend.
It’s working on the frontend also but it’s not displaying the content the user typed on the database
This is my frontend (Comment form) logic:
export default function AddComment({ busy}) {
const [content, setContent] = useState("");
const { movieId } = useParams();
const { updateNotification } = useNotification();
const handleOnChange = ({ target }) => {
setContent(target.value);
};
const handleSubmit = async (e) => {
e.preventDefault();
const { error, message } = await addComment(movieId);
if (error) return updateNotification("error", error);
updateNotification("success", message);
const newComment = {
content,
};
setContent(newComment);
setContent("");
};
return (
<div className='p-5'>
<br />
<p className='dark:text-white text-primary'>replies</p>
<hr className='w-64' />
{/* Comment Lists */}
{/* Root Comment Form */}
{/* Form */}
<form className='flex ' onSubmit={handleSubmit} busy={busy}>
<textarea
value={content}
onChange={handleOnChange}
type='text'
autoComplete='text'
className='w-full rounded-md p-2 dark:text-white text-primary outline-none bg-transparent resize-none border-b focus:border-blue-500'
placeholder='Add New comment'
/>
<br className='dark:text-white text-primary ' />
<button
type='submit'
className=' w-5 h-14 dark:text-white text-primary bg-blue-600 hover:bg-blue-400 focus:border-blue-900 rounded-md'
>
{busy ? <ImSpinner3 className='animate-spin' /> : "Add"}
</button>
</form>
</div>
);
}
Then the addComment is coming from this API:
import { catchError, getToken } from "../utils/helper";
import client from "./client";
export const addComment = async (movieId, newComment) => {
const token = getToken();
try {
const { data } = await client.post(
`/comments/comment/${movieId}`,
newComment,
{
headers: {
authorization: "Bearer " + token,
},
}
);
return data;
} catch (error) {
return catchError(error);
}
};
The backend is working:
exports.createComment = expressAsyncHandler(async (req, res) => {
const { movieId } = req.params;
const { content } = req.body;
const userId = req.user._id;
console.log(req.body);
// verify user before comment
if (!req.user.isVerified)
return sendError(res, "Please verify your email first!");
if (!isValidObjectId(movieId)) return sendError(res, "Invalid Movie!");
// create and update new comment
const newComment = new Comment({
user: userId,
parentMovie: movieId,
content,
});
// save new comment
await newComment.save();
res.json({ message: "New comment added!!", newComment });
});
I posted with Postman on backend it gave me this on the database:
_id
:
62dcfccd93444cef55611632
user
:
62bf20d65073a7c65f549078
parentMovie
:
62c2c425465804ff32cdd06c
content
:
"hello"
createdAt
:
2022-07-24T08:03:25.666+00:00
updatedAt
:
2022-07-24T08:03:25.666+00:00
__v
:
0
on the console:
The port is listening on port 8000
connected to db
{ content: 'hello' }
POST /api/comments/comment/62c2c425465804ff32cdd06c 200 447.534 ms - 260
I posted on the frontend it gave me this on the database, no content:
_id
:
62dcfd6993444cef55611635
user
:
62bf57e8a8f3e737b2af23d9
parentMovie
:
62cc1d426785cfe42f8737a8
createdAt
:
2022-07-24T08:06:01.458+00:00
updatedAt
:
2022-07-24T08:06:01.458+00:00
__v
:
0
on the console it shows an empty object:
{}
POST /api/comments/comment/62cc1d426785cfe42f8737a8 200 364.009 ms - 242
This is how I solved the problem
Hope this solution will help many
const handleSubmit = async (e) => {
e.preventDefault();
const { error, message } = await addComment(movieId, content); // call the content and movieId from backend
if (error) return updateNotification("error", error);
updateNotification("success", message);
// push and display the content on database
const newComment = {
content,
};
setContent(newComment);
setContent("");
};
Then the API should be like this
export const addComment = async (movieId, newComment) => {
const token = getToken();
// console.log(newComment);
const body = {
content: newComment,
};
try {
const { data } = await client.post(`/comments/comment/${movieId}`, body, {
headers: {
authorization: "Bearer " + token,
},
});
return data;
} catch (error) {
return catchError(error);
}
};

POST request error: Path `title` and `body` are required

I'm trying to make a POST request to my server to create a new post (title, body) and save it in the db and I'm receiving a 200 status code however the title and body aren't being inserted into a post.
UPDATE: I have just changed return res.status(400).json({ error: errorHandler(err) }) in the controller method to res.send(err) and now I'm receiving a clear error message: The title and body paths are required.
How can I solve this?
CreatePost.js
class CreatePost extends React.Component {
constructor(props) {
super(props)
this.state = {
title: '',
body: ''
}
}
changeHandler = (e) => {
this.setState({ [e.target.name]: e.target.value })
}
submitHandler = e => {
e.preventDefault()
axios.post(`${API}/blog/post/create`, this.state)
.then(response => {
console.log(response)
}).catch(error => {
console.log(error)
})
}
render() {
const {title, body} = this.state
return (
<div>
<form onSubmit={this.submitHandler}>
<input type="text" name="title"
onChange={this.changeHandler} value={title} />
<input type="text" name="body"
onChange={this.changeHandler} value={body}/>
<button type="submit">Submit</button>
</form>
</div>
)
}
}
export default CreatePost
controllers/post.js
exports.create = (req, res) => {
let post = new Post()
post.save((err, result) => {
if(err) {
return res.status(400).json({
error: errorHandler(err)
})
}
res.json(result)
})
}
routes/posts.js
router.post('/blog/post/create', create);
Did you try to call your endpoint from Postman or Insomnia (my favorite) to verify it is up and running? This is a great method to test your endpoints independently from your code.
Since you don't use HTTP 404 in your code, I suspect it is coming from the inner mechanisms of Express.
By the way, the verb POST and the 'create' part in your API uri are stating the same intent. You could get rid of this create part. This is considered one of the best practices.
Try with this.
axios({ url: `${API}/blog/post/create`, method: 'POST', data: this.state})
I've solved the issue. I wasn't actually inserting the title and body into the post object.
I destructured title and body from req.body:
const {title, body} = req.body and inserted the data into the object let post = new Post({title, body}).
controllers/posts.js
exports.create = (req, res) => {
const {title, body} = req.body
let post = new Post({title, body})
post.save()
.then(response => {
res.send(response)
.catch(err => {
res.send(err)
})
})
}

mern - updated values are null in data

I'm trying to update the posts. The PUT request in the back end works fine, returning 200 and updates posts when tested on Postman however when I try to update a post in the front end (react), I'm not receiving any errors but the updated post isn't being updated on submit and the updated fields (title and body) are null. The updated values are null when I console.log(data) in the front end which is why they aren't being sent to the back end but they are shown correctly in post.
Why are the updated values null inside data? How can I update the post with the new values instead of getting null?
data:
post:
Updated code: Frontend
const EditPost = ({match}) => {
const [values, setValues] = useState({
title: "",
body: "",
error: ""
});
const [post, setPost] = useState({});
const { user, token } = isAuthenticated();
const {
title,
body,
error,
} = values;
const init = (id) => {
read(id).then(data => {
if (data.error) {
setValues({...values, error: data.error})
} else {
setValues({...values,
title: data.title,
body: data.body,
})
setPost({title: values.title, body: values.body})
}
})
}
useEffect(() => {
const id = match.params.id;
init(id);
}, []);
useEffect(() => {
setPost({...values });
}, [values.title, values.body]);
const handleChange = (name) => (event) => {
setValues({ ...values, [name]: event.target.value });
};
const clickSubmit = (event) => {
event.preventDefault();
setValues({ ...values, error: "" });
editPost(match.params.userId, match.params.id, token, post).then((data) => {
if (data.error) {
setValues({ ...values, error: data.error });
} else {
setValues({
...values,
title: "",
body: "",
error: false,
});
console.log(post)
console.log(data)
}
});
};
const newPostForm = () => (
<form onSubmit={clickSubmit}>
<div>
<input
onChange={handleChange("title")} type="text"
name="title"
value={title}
/>
</div>
<div className="form-group">
<textarea
onChange={handleChange("body")}
value={body} name="body"
/>
</div>
<button type="submit">Publish</button>
</form>
);
const showError = () => (
<div
style={{ display: error ? "" : "none" }}>
{error}
</div>
);
return (
<div>
{showError()}
{newPostForm()}
</div>
);
};
export default EditPost;
export const editPost = (userId, id, token, post) => {
return fetch(`${API}/${userId}/${id}/edit`, {
method: 'PUT',
headers: {
Accept: 'application/json',
Authorization: `Bearer ${token}`
},
body: JSON.stringify(post)
})
.then(response => {
return response.json();
})
.catch(err => console.log(err));
};
postsByUser.js
<Link className="mypost_btn edit_btn" to={`/${_id}/${post._id}/edit`}>
Edit
</Link>
Backend code
exports.edit = (req, res) => {
if (!ObjectID.isValid(req.params.id))
return res.status(400).send(`ID is not valid: ${req.params.id}`)
const {title, body} = req.body
const updatedPost = {title, body }
Post.findByIdAndUpdate(req.params.id, {
$set: updatedPost
}, {new:true}, (error, data) => {
if (error) {
return error
} else {
res.send(data)
console.log(data)
}
})
}
Your problem lies here:
editPost(match.params.userId, match.params.id, token, post)
post is not defined.
Since post is not defined, no data is passed. Hence title and body equal to null. What you will need to do is, assuming from what I'm seeing on your code, is to define a state variable called post. I think you intended to do that:
const [post, setPost] = useState({values.title, values.body});
Then ensure that your post is updated whenever your values change using useEffect(),
useEffect(() => {
setPost({...values });
}, [values.title, value.body]);
So by the time you call your editPost() http-put-method, then post has a value. And it should work.
in EditPost.js editPost(match.params.userId, match.params.id, token).then((data) => { here you are missing the 4th arg which is the "post" it self you send to be updated

How to send data from React front-end to Nodejs Express back-end on button click

Disclaimer: I am new to React and Nodejs and have of course looked at all the current similar posts but none of them were able to help me fully so please don't mark as duplicate.
In my Nodejs index.js I have:
app.get('/list-certs', function (req, res) {
fs.readFile("certs.json", 'utf8', function (err, data) {
console.log( data );
res.send( data );
});
})
app.post('/list-certs', function (req, res) {
res.send('POST request: ' + req.body.domain-input);
console.log('post is working!')
});
And in my React App.js I have:
componentDidMount() {
this.callApi()
.then(res => {
this.setState({
json: res.map(x => x),
})
})
.catch(err => console.log(err));
}
callApi = async () => {
const response = await fetch('/list-certs');
const body = await response.json();
if (response.status !== 200) throw Error(body.message);
return body;
};
handleChange(event) {
this.setState({domainInputValue: event.target.value});
}
click() {
}
render() {
return (
<div className="App">
<form action="http://127.0.0.1:8000/list-certs" className="add-cert-form" method="post">
<h1>Add new domain</h1>
<h5 className="domain-label">Name:</h5>
<Input className="domain-input" value={this.state.domainInputValue} onChange={(e) => {this.handleChange(e)}}></Input>
<Button onClick={this.click} className="domain-button" type='primary'>Add</Button>
</form>
.
.
.
}
How do I send the data in my input field domain-input to my back-end when the button domain-button is clicked? I know something needs to go in the click() but I'm not sure what.
Any help is appreciated!
Your click function will look like it:
async click() {
const { domainInputValue } = this.state;
const request = await fetch('/echo/json', {
headers: {
'Content-type': 'application/json'
},
method: 'POST',
body: { domainInputValue }
});
}

Why are vote options not correctly pre-selected? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
You need to be authenticated to vote on a poll. When you vote on a poll, there are 2 issues:
You can vote an infinite number of times until you leave or reload the page
When you reload the page, you are finally prevented from voting but instead of having the option you voted on pre-selected, it's always the second option that is preselected.
WHAT SHOULD HAPPEN:
Sign up/ Login, then vote on a poll. The moment you click on an option, the poll voting choice you made is locked and you can't vote more on that poll.
HOW THE FLOW OF MY CURRENT CODE WORKS:
When a user clicks on an option, the counter is increased and the vote is then saved in an array that is pushed to the User object in the database.
When the component loads, the database data for votes for the currently logged in user is saved through the ngOninit() method inside the local votes variable which is then used to check on which poll the user already voted and what vote he made. The issue is that the choice is made is always choice2 when that is not actually the case.
I understand why you can vote many times until the page reloads, but I just don't know how to immediately lock the poll after the user voted, on the client and on the backend (prevent more votes from being registered if user already voted on poll).
As for why it is already the second choice that is pre-selected, I have no idea.
CODE:
HTML
<div class="formWidth">
<form (ngSubmit)="onSubmit(f)" #f="ngForm">
<div class="form-group">
<label class="inputTitle" for="title">Poll Title</label>
<input
type="text"
id="title"
class="form-control"
[ngModel]="poll?.title"
name="title"
required maxlenth="30">
<label class="inputTitle" for="choice1">Choice1</label>
<input
type="text"
id="choice1"
class="form-control"
[ngModel]="poll?.choice1"
name="choice1"
required maxlenth="20">
<label class="inputTitle" for="choice2">Choice2</label>
<input
type="text"
id="choice2"
class="form-control"
[ngModel]="poll?.choice2"
name="choice2"
required maxlenth="20">
</div>
<button type="button" class="btn btn-danger" (click)="onClear(f)">Clear</button>
<button class="btn btn-primary" type="submit">Save</button>
</form>
</div>
COMPONENT
export class PollComponent {
#Input() poll: Poll;
constructor(private pollService: PollService) {}
votes: any;
// Pie
public pieChartLabels:string[] = [];
public pieChartData:number[] = [];
public pieChartType:string = 'pie';
public pieChartOptions:any = {};
ngOnInit() {
var result1 = parseFloat(((this.poll.counter1/(this.poll.counter2+this.poll.counter1))*100).toFixed(2));
var result2 = parseFloat(((this.poll.counter2/(this.poll.counter2+this.poll.counter1))*100).toFixed(2));
this.pieChartData = [result1, result2];
this.pieChartLabels = [this.poll.choice1, this.poll.choice2];
this.pieChartType = 'pie';
this.pieChartOptions = {
tooltips: {
enabled: true,
mode: 'single',
callbacks: {
label: function(tooltipItem, data) {
var allData = data.datasets[tooltipItem.datasetIndex].data;
var tooltipLabel = data.labels[tooltipItem.index];
var tooltipData = allData[tooltipItem.index];
return tooltipLabel + ": " + tooltipData + "%";
}
}
}
}
this.pollService.voted(localStorage.getItem('userId')).subscribe(
data => {
var result = JSON.parse(data);
this.votes = result.votes;
},
err => { console.log("NGONINIT ERROR: "+ err) },
() => { }
);
}
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();
var result1 = parseFloat(((this.poll.counter1/(this.poll.counter2+this.poll.counter1))*100).toFixed(2));
var result2 = parseFloat(((this.poll.counter2/(this.poll.counter2+this.poll.counter1))*100).toFixed(2));
this.pieChartData = [result1, result2];
}
onChoice2() {
this.pollService.increaseCounter2(this.poll);
this.onVote2();
var result1 = parseFloat(((this.poll.counter1/(this.poll.counter2+this.poll.counter1))*100).toFixed(2));
var result2 = parseFloat(((this.poll.counter2/(this.poll.counter2+this.poll.counter1))*100).toFixed(2));
this.pieChartData = [result1, result2];
}
onVote1() {
this.pollService.voteOn(this.poll.pollID, localStorage.getItem('userId'), 1);
}
onVote2() {
this.pollService.voteOn(this.poll.pollID, localStorage.getItem('userId'), 2);
}
belongsToUser() {
return localStorage.getItem('userId') == this.poll.userId;
}
alreadyVotedFor(choice: number) {
var result = "";
if (this.votes) {
for (var i = 0; i < this.votes.length; i ++) {
if (this.votes[i].pollID == this.poll.pollID) {
result = "disabled";
if (this.votes[i].choice == choice) {
result = "selected";
}
}
}
}
return result;
}
// events
public chartClicked(e:any):void {
}
public chartHovered(e:any):void {
}
}
SERVICE
updatePoll(poll: Poll) {
const body = JSON.stringify(poll);
const token = localStorage.getItem('token')
? localStorage.getItem('token')
: '';
const headers = new Headers({
'Content-Type': 'application/json',
'Authorization': 'Bearer '+token
});
return this.http.patch('https://voting-app-10.herokuapp.com/poll/' + poll.pollID, body, {headers: headers})
.map((response: Response) => response.json())
.catch((error: Response) => {
this.errorService.handleError(error.json());
return Observable.throw(error);
});
}
increaseCounter1(poll: Poll) {
poll.counter1++;
const body = JSON.stringify(poll);
const token = localStorage.getItem('token')
? localStorage.getItem('token')
: '';
const headers = new Headers({
'Content-Type': 'application/json',
'Authorization': 'Bearer '+token
});
this.http.patch('https://voting-app-10.herokuapp.com/poll/vote/' + poll.pollID, body, {headers: headers})
.map((response: Response) => response.json())
.catch((error: Response) => {
this.errorService.handleError(error.json());
return Observable.throw(error);
})
.subscribe();
}
increaseCounter2(poll: Poll) {
poll.counter2++;
const body = JSON.stringify(poll);
const token = localStorage.getItem('token')
? localStorage.getItem('token')
: '';
const headers = new Headers({
'Content-Type': 'application/json',
'Authorization': 'Bearer '+token
});
return this.http.patch('https://voting-app-10.herokuapp.com/poll/vote/' + poll.pollID, body, {headers: headers})
.map((response: Response) => response.json())
.catch((error: Response) => {
this.errorService.handleError(error.json());
return Observable.throw(error);
})
.subscribe();
}
voteOn(pollID: string, userID: string, choice: number) {
var user;
this.http.get('https://voting-app-10.herokuapp.com/user/'+userID)
.map(response => response.json())
.subscribe(
json => {
user = JSON.parse(json);
if (user.votes == undefined) {
user.votes = [{pollID, choice}];
} else {
user.votes.push({pollID, choice});
}
const body = user;
const token = localStorage.getItem('token')
? localStorage.getItem('token')
: '';
const headers = new Headers({
'Content-Type': 'application/json',
'Authorization': 'Bearer '+token
});
return this.http.patch('https://voting-app-10.herokuapp.com/user/', body, {headers: headers})
.map((response: Response) => response.json())
.catch((error: Response) => {
this.errorService.handleError(error.json());
return Observable.throw(error);
})
.subscribe();
}
)
}
voted(userID: string) {
const headers = new Headers({'Content-Type': 'application/json'});
return this.http.get('https://voting-app-10.herokuapp.com/user/'+userID,{headers: headers})
.map(response => response.json())
.catch((error: Response) => {
this.errorService.handleError(error.json());
return Observable.throw(error);
});
}
ROUTE (BACKEND)
router.patch('/vote/:id', function (req, res, next) {
var decoded = jwt.decode(getToken(req));
Poll.findById(req.params.id, function (err, poll) {
if (err) {
return res.status(500).json({
title: 'An error occurred',
error: err
});
}
if (!poll) {
return res.status(500).json({
title: 'No Poll Found!',
error: {poll: 'Poll not found'}
});
}
poll.title = req.body.title;
poll.choice1 = req.body.choice1;
poll.choice2 = req.body.choice2;
poll.counter1 = req.body.counter1;
poll.counter2 = req.body.counter2;
poll.save(function (err, result) {
if (err) {
return res.status(500).json({
title: 'An error occurred',
error: err
});
}
res.status(200).json({
poll: 'Updated poll',
obj: result
});
});
});
});
router.patch('/:id', function (req, res, next) {
var decoded = jwt.decode(getToken(req));
Poll.findById(req.params.id, function (err, poll) {
if (err) {
return res.status(500).json({
title: 'An error occurred',
error: err
});
}
if (!poll) {
return res.status(500).json({
title: 'No Poll Found!',
error: {poll: 'Poll not found'}
});
}
if (poll.user != decoded.user._id) {
return res.status(401).json({
title: 'Not Authenticated',
error: {poll: 'Users do not match'}
});
}
poll.title = req.body.title;
poll.choice1 = req.body.choice1;
poll.choice2 = req.body.choice2;
poll.counter1 = req.body.counter1;
poll.counter2 = req.body.counter2;
poll.save(function (err, result) {
if (err) {
return res.status(500).json({
title: 'An error occurred',
error: err
});
}
res.status(200).json({
poll: 'Updated poll',
obj: result
});
});
});
});
Okay, at first your radio buttons don't get disabled, because you don't update the votes-array in your poll.component.ts after saving a vote.
I'm not sure if it's a good solution or not:
In your poll.service.ts:
voteOn(pollID: string, userID: string, choice: number) {
var user;
return new Promise((resolve) => { //Create a new promise to wrap the Subscriptions
this.http.get('http://localhost:3000/user/' + userID)
.map(response => response.json())
.subscribe(
json => {
user = JSON.parse(json);
if (user.votes == undefined) {
...
.catch((error: Response) => {
this.errorService.handleError(error.json());
return Observable.throw(error);
}).subscribe(() => {
resolve(user.votes); // <- Resolve your promise
})
}
)
});
}
And in your poll.component.ts:
voteOn(...).then((votes) => {
this.votes = votes; // To update your votes array
this.updateVote();
})
And I don't recommend to call functions in bindings, because it happens that the functions are called very often "to detect changes", like in your components.
So I would change the code in following way:
In your poll.component.ts:
vote:any //Added to your poll component
updateVote() {
this.vote = this.votes.find((vote) => {
return vote.pollID === this.poll.pollID;
});
}
You need to call this method in your ngOnInit method:
this.pollService.voted(localStorage.getItem('userId')).subscribe(
data => {
var result = JSON.parse(data);
this.votes = result.votes;
this.updateVote(); // <- To select the vote of this poll
},
err => { console.log("NGONINIT ERROR: " + err) },
() => { }
);
And in your poll.component.html:
<fieldset [disabled]="vote">
{{ poll.counter1 }} votes <input type="radio" id="{{ poll.choice1 }}" name="my_radio" value="{{ poll.choice1 }}" (click)="onChoice1(form)" [checked]="vote?.choice == 1"> {{ poll.choice1 }}
<br>
{{ poll.counter2 }} votes <input type="radio" id="{{ poll.choice2 }}" name="my_radio" value="{{ poll.choice2 }}" (click)="onChoice2(form)" [checked]="vote?.choice == 2"> {{ poll.choice2 }}
</fieldset>
But if you don't want to change your code in such a way, please tell me, so i can provide another solution.

Resources