angular - 使用 ngFor 可观察角度
问题描述
我正在使用 Angular 构建一个简单的 Web 应用程序。在我的模板中,我想显示教师列表。
从服务器我得到这种json()
{ users : [{user1}, {user2}, {user3} ] }
这是我的服务文件。
@Injectable()
export class StudentService {
constructor(
private http: Http
) { }
getAllTeachers() {
return this.http.get('https://guarded-beyond-19031.herokuapp.com/search');
}
}
在控制器内部我调用getAllTecher()
函数。这是我的控制器文件。
import { Component, OnInit } from '@angular/core';
import { StudentService } from 'src/app/common/services/student.service';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
@Component({
selector: 'app-home-student',
templateUrl: './home-student.component.html',
styleUrls: ['./home-student.component.scss']
})
export class HomeStudentComponent implements OnInit {
teachers$: Observable<Array<any>>;
constructor(
private studentService: StudentService
) {
this.teachers$ = this.studentService.getAllTeachers();
}
ngOnInit() {}
}
在 html 模板内部,我使用了async
管道。这是我的模板文件。
<div *ngFor='let teacher of teachers| async'>
{{teacher.name}}
</div>
但是在我的控制器文件中,在这一行
this.teachers$ = this.studentService.getAllTeachers();
我收到如下错误。
Type 'Observable<Response>' is not assignable to type 'Observable<any[]>'.
Type 'Response' is not assignable to type 'any[]'.
Property 'length' is missing in type 'Response'.
(property) HomeStudentComponent.teacherCards$: Observable<any[]>
我的代码有什么问题,我该如何解决?
解决方案
您的响应是一个对象,您需要使用 map 运算符来更改结果的类型,在 ngFor 中使用它,只需将返回类型更新getAllTeachers
为Observable<any[]>
getAllTeachers() : Observable<any[]> {
return this.http.get('https://guarded-beyond-19031.herokuapp.com/search')
.pipe(map(result => result.user));
}
abd 以这种方式更新教师 $ 属性
teachers$: Observable<any[]>;
推荐阅读
- r - 有没有办法“自我更新”多年未更新的软件包?
- angular - 如何将一组 Observable 合并为一个具有相同返回类型的 Observable
- php - 使用个人访问令牌访问 laravel api 时出现内部服务器错误 [500]
- sql - 如何在触发器中使用更新表中的数据?
- r - igraph contract_vertices 在交互过程中的不同点抛出类型错误
- python - Looping through html with beautiful soup in Python
- android - Android Studio:右键单击并运行测试始终默认为 Gradle 配置
- java - 复制所选 JTable 单元格的单元格值而不是行
- python - 从 2 个文本文件中删除相同的文本
- c++ - CMAKE 错误:“无法打开源文件”:“CMakeCCompilerId.c”