已关闭。此问题为opinion-based。目前不接受回答。
**要改进此问题吗?**更新此问题,以便editing this post可以使用事实和引文来回答。
昨天就关门了。
Improve this question的
我正在学习angular,我想知道是否可以使用axios向server发出http请求。这是可行的,但我很困惑在angular中使用axios是否是一个糟糕的做法。我想知道我是否可以继续这样做或使用HttpClient和subscriber模型。使用这种方法有什么缺点吗?我发现的大多数教程都使用httpClient和subscriber模型。而这似乎更容易理解,特别是对像我这样的初学者。
import { Injectable } from '@angular/core';
import { Student } from './models/Student';
import { students } from './models/StudentList';
import axios from 'axios';
@Injectable({
providedIn: 'root'
})
export class StudentService {
students: Student[] = students;
// adding a new student
public addStudent(name: string) {
const addStudent = async (name: string) => {
try {
const response = await axios({
method: 'POST',
url: 'http://localhost:8080/student/add',
data: {
'name': name
}
});
if (response.status === 201) {
alert('student added');
}
}
catch (err) {
console.log(err);
}
}
addStudent(name);
}
// getting list of all the students
public getAllStudents(): Student[] {
const studentList: Student[] = [];
const getAllStudentsAxios = async () => {
try {
const response = await axios({
method: 'GET',
url: 'http://localhost:8080/student/all'
});
// console.log(response.data);
for (let responseObject of response.data) {
const student: Student = new Student();
student.id = responseObject.id;
student.name = responseObject.name;
studentList.push(student);
}
}
catch (err) {
console.log(err);
}
}
getAllStudentsAxios();
return studentList;
}
// getting student by id
public getStudentById(id: number): Student {
const student : Student = new Student();
const getStudentByIdAxios = async () => {
try {
const url = 'http://localhost:8080/student/' + id;
const response = await axios({
method: 'GET',
url: url
});
student.id = response.data.id;
student.name = response.data.name;
}
catch (err) {
console.log(err);
}
}
getStudentByIdAxios();
return student;
}
// get courses registered by student
// student registering a course
public registerCourse(student_id: Number, course_id: number): void {
alert('course registered ' + student_id + course_id);
}
public submitReview(student_id: Number, course_id: Number, rating: Number, review: string) {
alert(student_id + ' ' + rating + ' ' + review + ' ' + course_id);
}
public deleteCourse(student_id: Number, course_id: Number) {
alert(student_id + ' ' + course_id);
}
constructor() { }
}
字符串
3条答案
按热度按时间jgzswidk1#
如果你想遵循Angular的最佳实践,你应该考虑使用HttpClient和Observable模式。这里有一个快速的例子,你可以如何使用HttpClient重写你的getAllStudents方法:
字符串
r1wp621o2#
在Angular中使用Axios绝对是可能的,但这不是一个常见的做法,也不推荐。
Angular的内部依赖于你使用
HttpClient
(对于ApplicationRef.isStable
等)。mftmpeh83#
在angular中使用axios是完全可以的,但httpClient将是最佳实践。