3

I'm building a simple web application using angular. In my template i want to show a list of teachers.

From the server i'm getting this kind of 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. 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. 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?

Buddhika Chathuranga
  • 1,334
  • 2
  • 13
  • 22

3 Answers3

2

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

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

  teachers$: Observable<any[]>;
Muhammed Albarmavi
  • 23,240
  • 8
  • 66
  • 91
1

add return type for function

getAllTeachers(): Observable<Array<any>> {
Sachila Ranawaka
  • 39,756
  • 7
  • 56
  • 80
1

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"]))          
    }
Sunil Singh
  • 11,001
  • 2
  • 27
  • 48