【发布时间】:2018-04-16 04:50:14
【问题描述】:
我正在学习 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
【问题讨论】:
-
奥普斯。这里是:
-
我认为您可以尝试
return this.httpClient.get<Course[]>('https://jsonplaceholder.typicode.com/posts'); }来强输入您的 API 答案。 -
感谢 Yanis-git。像魅力一样工作!
标签: angular typescript mean-stack