Typescript错误:类型Observable <object>不能分配给type

时间:2018-04-16 04:50:14

标签: angular typescript mean-stack

我正在学习MEAN堆栈而且我已经停留在一段曾经工作过的代码上,但是为了理由,它似乎不想为我工作。

我收到错误:&#34; Type Observable不能分配给Observable类型。你的意思是使用&#39; any&#39;改为输入?

这是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

2 个答案:

答案 0 :(得分:2)

在原始问题的评论中指定,在这种情况下你可以像这样强力投射httpClient observable:

@Injectable() 
export class CourseService {

    constructor(private httpClient: HttpClient) { }

    readAll(): Observable<Course[]> {
        return this.httpClient
            .get<Course[]>('https://jsonplaceholder.typicode.com/posts');   
        }
}

通过这种方式,您将收到Observable<Object>

来接收Observable<Course[]>

您可以使用另一个案例强制您从请求答案中应用某些转换以适合您的模型,在这种情况下,您应该使用map运算符。将看起来像这样:

@Injectable() 
export class CourseService {

    constructor(private httpClient: HttpClient) { }

    readAll(): Observable<Course[]> {

        return this.httpClient
            .get<MyType[]>('https://jsonplaceholder.typicode.com/posts').pipe(map(myAnswers => {
                    /**
                     * Map operator is dedicated to transform original data to formated data who fit on your expected output.
                    **/
                    const myTransformedAnswer = [];

                    myAnswers.forEach((item) => {
                        myTransformedAnswer.push({
                            id: item.id,
                            title: item.foo,
                            description: item.bar
                        });
                    });

                    return myTransformedAnswer;
            }));   
        }
}

答案 1 :(得分:0)

事情是httpClient直接返回Observable<HttpResponse<Course[]>>而不是Observable<Course[]>,所以你的类型不匹配。

你也可以这样做:

return this.httpClient
    .get<Course[]>.('https://jsonplaceholder.typicode.com/posts');

因此,如果您对其返回的内容执行更多操作,您也会在readAll()

中输入类型

所以你的readAll()应该这样:

readAll(): Observable<HttpResponse<Course[]>> {
    return this.httpClient
        .get<Course[]>('https://jsonplaceholder.typicode.com/posts');   }