我正在尝试通过API将对象传递给我的组件。 在服务中,数据是完整的
但是当我试图在组件和console.log中获取数据时。我得到的是不确定的
我想念什么?为什么函数返回注释。毕竟我要从服务器获取数据
组件:
export class ClassesComponent implements OnInit {
lessons: Lesson[] = [];
lessonsPerPage = 16;
currentPage = 1;
constructor(private lessonsService: LessonsService) {
}
ngOnInit() {
console.log(this.lessonsService.getLessons(this.lessonsPerPage, this.currentPage)); // undifined
this.lessons = this.lessonsService.getLessons(this.lessonsPerPage, this.currentPage);
console.log(this.lessons); // undifined
}
}
服务:
export class LessonsService {
private lessons: Lesson[] = [];
private lessonUpdated = new Subject<{ lessons: Lesson[]; lessonCount: number }>();
constructor(private http: HttpClient) { }
getLessons(lessonsPerPage: number, currentPage: number) {
const queryParams = `?pagesize=${lessonsPerPage}&page=${currentPage}`;
this.http
.get<{ message: string, lessons: any, maxLessons: number }>
('http://localhost:3000/api/lessons')
.pipe(map(lessonData => {
return {
lessons: lessonData.lessons.map(lesson => {
return {
id: lesson.id,
title: lesson.title,
content: lesson.content,
startDate: lesson.startDate,
endDate: lesson.endDate,
hoursStart: lesson.hoursStart,
hoursEnd: lesson.hoursEnd,
location: lesson.location,
price: lesson.price,
numberOfSessions: lesson.numberOfSessions
};
}),
maxLessons: lessonData.maxLessons
};
})
)
.subscribe(transformedLesson => {
this.lessons = transformedLesson.lessons;
console.log(this.lessons)
this.lessonUpdated.next({
lessons: [...this.lessons],
lessonCount: transformedLesson.maxLessons
});
});
}
}
好。即使最简单的调用也没有传递任何数据,这对我来说还是很奇怪的
return this.http.get('http://localhost:3000/api/lessons')
.subscribe(res => {
// console.log(res.lessons);
this.lessonsArr.push(res.lessons);
console.log(this.lessonsArr);
});
答案 0 :(得分:0)
您不应在服务内订阅HTTP请求,因为您只需要返回组件本身上的值即可。
export class LessonsService {
constructor(private http: HttpClient) {}
getLessons(lessonsPerPage: number, currentPage: number) {
const queryParams = `?pagesize=${lessonsPerPage}&page=${currentPage}`;
return this.http.get <{ message: string, lessons: any, maxLessons: number }> ('http://localhost:3000/api/lessons')
.pipe(map(lessonData => {
return {
lessons: lessonData.lessons.map(lesson => {
return {
id: lesson.id,
title: lesson.title,
content: lesson.content,
startDate: lesson.startDate,
endDate: lesson.endDate,
hoursStart: lesson.hoursStart,
hoursEnd: lesson.hoursEnd,
location: lesson.location,
price: lesson.price,
numberOfSessions: lesson.numberOfSessions
};
}),
maxLessons: lessonData.maxLessons
};
}));
}
}
在component.ts
上,您需要订阅service方法以从HTTP请求中返回可观察的值。
ngOnInit() {
this.lessonsService.getLessons(this.lessonsPerPage, this.currentPage).subscribe(res => {
// do the rest here
this.lessons = res;
});
}