简体   繁体   English

使用ngFor可观察角度

[英]Angular observable with ngFor

I'm building a simple web application using angular. 我正在使用angular构建一个简单的Web应用程序。 In my template i want to show a list of teachers. 在我的模板中,我想显示一个教师列表。

From the server i'm getting this kind of json() 从服务器我得到这种json()

{ users : [{user1}, {user2}, {user3} ] }

this is my service file. 这是我的服务文件。

@Injectable()
export class StudentService {

    constructor(
        private http: Http
    ) { }

    getAllTeachers() {
        return this.http.get('https://guarded-beyond-19031.herokuapp.com/search');            
    }

}

Inside the controller i call getAllTecher() function. 在控制器内部,我调用getAllTecher()函数。 This is my controller file. 这是我的控制器文件。

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() {}

}

Inside of the html template i have use an async pipe. 在html模板里面我使用了async管道。 This is my template file. 这是我的模板文件。

<div *ngFor='let teacher of teachers| async'>
    {{teacher.name}}
</div>

But in my controller file, in this line 但在我的控制器文件中,在这一行

this.teachers$ = this.studentService.getAllTeachers();

i'm getting an error as given below. 我收到的错误如下所示。

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[]>

whats the wrong with my code and how can i fix that? 我的代码有什么问题,我该如何解决?

Your response is an object you need to use map operator in order to change the type of the result any use it in ngFor and just update the return type of getAllTeachers to 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 update teachers$ property to this way abd以这种方式更新教师$ property

  teachers$: Observable<any[]>;

添加函数的返回类型

getAllTeachers(): Observable<Array<any>> {

The issue with response set of wrong type, you are assigning the object to array. 响应集的错误类型的问题,您将对象分配给数组。

 getAllTeachers() {
        return this.http.get('https://guarded-beyond-19031.herokuapp.com/search')
       .pipe(map(response=>response["users"]))          
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM