无法将Object []分配给Observable <object []>

时间:2017-10-25 02:54:27

标签: javascript angular typescript

我目前正在通过一个Angular 4项目笨手笨脚。到目前为止,我已经设法克服了大多数错误,但是我无法弄清楚这一点。

我正在尝试使用* ngFor(async)来显示Observable对象列表。 但是,我收到错误“无法将课程[]分配给Observable&lt; Course []&gt;”,但我觉得我的服务正在返回一个Observable&lt;课程[]&gt;。

航向list.component.ts:

import { Component, OnInit } from '@angular/core';
import { Http } from '@angular/http';
import { CourseCardComponent } from '../course-card/course-card.component';
import { CourseCardService } from '../course-card/course-card.service';
import { CourseCard } from '../course-card/course-card.model';
import { Observable }     from 'rxjs/Observable';

@Component({
  selector: 'app-course-list',
  templateUrl: './course-list.component.html',
  styleUrls: ['./course-list.component.css']
})
export class CourseListComponent implements OnInit {
  courseCards : Observable<CourseCard[]>;
  loaded = false;

  constructor(private http:Http, private coursecardService:CourseCardService) { }

  ngOnInit() {
    this.coursecardService.getCourses()
    .subscribe(
      courses => {
        this.courseCards = courses;
        console.log(this.courseCards);
        this.loaded = true;
      },
      err => {
        console.log("Error", err);
      }
    )
  }
}

航向card.service.ts

import { Injectable }     from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable }     from 'rxjs/Observable';

import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';

import { CourseCard } from './course-card.model';

@Injectable()
export class CourseCardService {
    // Returns this JSON data:
    // [{"firstName":"Jane"},{"firstName":"John"}]
    private URL = '/api/getcourses';

    constructor (private http: Http) {}

    getCourses(): Observable<CourseCard[]> {
        return this.http.get(this.URL)
            .map((response) => {
            let data = response.text() ? response.json():[{}];
                if(data) {
                    return data;
                }
            }
        )
        .catch((error:any) => Observable.throw(error.json().error || 'Server error'));
    }
}

以及课程列表组件的HTML 课程

<ul>
  <li *ngFor="let course of courses|async">
    <app-course-card [name]='course.name' [wordcount]=0></app-course-card>
  </li>
</ul>

4 个答案:

答案 0 :(得分:3)

此部分确实返回Observable<CourseCard[]>

  

this.coursecardService.getCourses()

但是你手动订阅它,而在订阅内部,课程的类型为CourseCard[]。因此,当您尝试分配this.courseCards = courses;时,那就是当您遇到类型不匹配时。

异步管道将为您进行订阅,因此您可以将代码更改为:

ngOnInit() {
  this.courseCards = this.coursecardService.getCourses();
}

答案 1 :(得分:0)

没关系,我读了更多关于.subscribe方法的内容。它返回一个订阅对象,我只需将其更改为:

ngOnInit() {
    this.courseCards = this.coursecardService.getCourses();
  }

答案 2 :(得分:0)

您的列表属性名称是否正确? let course of courses或应该是 let course of courseCards

   <ul>
      <li *ngFor="let course of courseCards|async">
        <app-course-card [name]='course.name' [wordcount]=0></app-course-card>
      </li>
    </ul>

答案 3 :(得分:0)

试试这样:

getCourses(): Observable<CourseCard[]> {
    return this.http.get(this.URL)
        .map((response) => <CourseCard[]>response.json())
        .catch((error: any) => Observable.throw(error.json().error || 'Server error'));
}