我正在学习MEAN堆栈,并且停留在曾经可以正常工作的一段代码上,但是由于今天的原因,它似乎不想为我工作。
我收到一个错误消息:“不能将类型Observable分配给类型Observable。您是要使用'any'类型吗?
这是Course.service.ts文件,其中会出现错误:
import { Injectable } from '@angular/core';
import {Course} from './course';
import {Observable} from 'rxjs/Observable';
import {HttpClient} from '@angular/common/http';
@Injectable() export class CourseService {
constructor(private httpClient: HttpClient) { }
readAll(): Observable<Course[]> {
return this.httpClient
.get('https://jsonplaceholder.typicode.com/posts'); }
}
这是course.component.ts:
import {Component, Input, OnInit} from '@angular/core';
import {Course} from '../course';
@Component({
selector: 'app-course',
templateUrl: './course.component.html',
styleUrls: ['./course.component.css']
})
export class CourseComponent implements OnInit {
@Input()
course: Course;
@Input()
courseItemCss: string;
constructor() { }
ngOnInit() {
if (!this.course) {
this.course = <Course> {};
}
}
}
这是接口course.ts:
export interface Course {
id: string;
title: string;
description: string;
}
course.component.ts:
import {Component, Input, OnInit} from '@angular/core';
import {Course} from '../course';
@Component({
selector: 'app-course',
templateUrl: './course.component.html',
styleUrls: ['./course.component.css']
})
export class CourseComponent implements OnInit {
@Input()
course: Course;
@Input()
courseItemCss: string;
constructor() { }
ngOnInit() {
if (!this.course) {
this.course = <Course> {};
}
}
}
course.manager.component.ts:
import {Component, OnDestroy, OnInit} from '@angular/core';
import {Subscription} from 'rxjs/Subscription';
import {CourseService} from '../course.service';
import {Course} from '../course';
@Component({
selector: 'app-course-manager',
templateUrl: './course-manager.component.html',
styleUrls: ['./course-manager.component.css']
})
export class CourseManagerComponent implements OnInit, OnDestroy {
courses: Array<Course>;
courseServiceSub: Subscription;
constructor(private courseService: CourseService) {
this.courses = [];
}
ngOnInit() {
this.courseServiceSub = this.courseService.readAll().subscribe(courses => {
this.courses = courses;
});
}
ngOnDestroy() {
if (this.courseServiceSub) { // if subscription exists, unsubscribe from it.
this.courseServiceSub.unsubscribe(); // make sure to unsubscribe or may cause memory leaks which makes app slower.
}
}
}
我知道这很简单,但现在无法解决。任何建议都会有所帮助。谢谢!
〜jb
.subscribe((data: IUsers) => ...
或this.users = data as any;
– cyr_x 17年 7月31日,23:49data as any
在我的情况下做到了。 – negrotico18年 2月26日在22:58