gpt4 book ai didi

javascript - 无法将 Object[] 分配给 Observable

转载 作者:行者123 更新时间:2023-11-30 09:29:58 24 4
gpt4 key购买 nike

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

我正在尝试使用 *ngFor(异步)来显示 Observable 对象的列表。但是,我收到错误消息“无法将 Course[] 分配给 Observable ,但我觉得我的服务正在返回一个 Observable

类(class)列表.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);
}
)
}
}

类(class)卡.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'));
}
}

类(class)列表组件的 HTML类(class)

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

最佳答案

这部分返回一个 Observable<CourseCard[]> :

this.coursecardService.getCourses()

但随后您手动订阅它,在订阅中,类(class)类型为 CourseCard[] .因此,当您尝试分配 this.courseCards = courses; 时,这就是您遇到类型不匹配的时候。

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

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

关于javascript - 无法将 Object[] 分配给 Observable<Object[]>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46923190/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com