首页 > 解决方案 > 使用 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[]>

我的代码有什么问题,我该如何解决?

标签: angularasynchronousrxjspipeobservable

解决方案


您的响应是一个对象,您需要使用 map 运算符来更改结果的类型,在 ngFor 中使用它,只需将返回类型更新getAllTeachersObservable<any[]>

getAllTeachers() : Observable<any[]> {
        return this.http.get('https://guarded-beyond-19031.herokuapp.com/search')
         .pipe(map(result => result.user));            
 }

abd 以这种方式更新教师 $ 属性

  teachers$: Observable<any[]>;

推荐阅读