欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

Type 'Observable<Object>' is not assignable to type 'Observable<Project>'. The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead? Type 'Object' is missing the following properties from type 有大用 有大大用

 
活动时间 1年,5个月前    
已浏览 4k次    
1个                    

我正在学习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                    

                      

  • 哎呀。在这里是: – brohjoe 18年  4月16日在4:59                                
  • 2                                
    我认为您可以尝试return this.httpClient.get<Course[]>('https://jsonplaceholder.typicode.com/posts'); }强类型化您的API答案。 –  Yanis-git 18年4月16日在5:14                                 
  • 感谢Yanis-git。像魅力一样工作! – brohjoe 18年  4月16日在5:22                                
添加评论                
       

2个答案    正确答案                

活跃的最古老的选票                    
       
4                        

如在原始问题的注释中指定的,在这种情况下,您可以像下面这样强制转换httpClient可观察的:                        

@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个                        

问题是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');   }
                   

添加评论                    
       

来自  https://stackoverflow.com/questions/49849816/typescript-error-type-observableobject-is-not-assignable-to-type            


           


           

 
活动时间 1年,4个月之前                
已浏览 8k次                
6                                

将Angular项目从版本5更新到6后,出现以下错误:                                

类型Observable'<'Object>不能分配给类型Observable'<'Todo>。                                    

在我的todo.service.ts中                                

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { environment } from '../../../environments/environment';
import { Todo } from '../../../models/Todo';
import { Observable, of } from 'rxjs';
import { catchError } from 'rxjs/operators';
import 'rxjs/add/observable/throw';

@Injectable()
export class TodoService {

  todos: Todo[];

  constructor( private httpClient: HttpClient ) { }

  loadTodos(): Observable<Todo[]> {
    return this.httpClient.get<Todo[]>(`${environment.api}${environment.path}`).pipe(
      catchError((error: any) => Observable.throw(error))
    );
  }

  addTodo(todo: Todo): Observable<Todo> {
    return this.httpClient.post(`${environment.api}${environment.path}`, JSON.stringify(todo)).pipe(
      catchError((error: any) => Observable.throw(error))
    );
  }

  editTodo(todo: Todo): Observable<Todo> {
    return this.httpClient.put(`${environment.api}${environment.path}/${todo.id}`, JSON.stringify(todo)).pipe(
      catchError((error: any) => Observable.throw(error))
    );
  }

  deleteTodo(todo: Todo): Observable<Todo> {
    return this.httpClient.delete(`${environment.api}${environment.path}/${todo.id}`).pipe(
      catchError((error: any) => Observable.throw(error))
    );
  }
}
                               

错误指向addTodo,editTodo和deleteTodo方法,由于loadTodo将Observable'<'Object>类型分配给Observable'<'Array>类型,因此没有问题。我使用此链接来更改rxjs元素的导入方式,但没有成功。有什么帮助吗?                                

                                  

  • 4                                            
    尝试如何post<Todo[]> – Reactgular 18年  5月23日在16:12                                            
  • post <Todo []>意味着我们发布了一个数组,请您解释一下? –  Sami-L 18年5月23日在16:15                                            
  • 使用post<Todo[]>将意味着发布请求将返回一个Todo数组。您在体内发布的内容无关紧要,也不会改变。 –  Jun Kang '18 May 23'在16:37                                            
  • 尝试使用<Todo>投射帖子,放置和删除方法。例如:http.post <Todo>() –  周特兰 18年5月23日在16:40                                            
  • 1个                                            
    就像您对get方法所做的一样,除了Todo而不是Todo []之外,其他所有操作均要执行此操作 –  Chau Tran 18年5月23日,16:50                                            
再显示1条评论                            
                   

1个回答                             

正确答案                            


                           

活跃的最古老的选票                                
                   
9                                    

httpClient方法是通用的,您必须键入响应,例如:                                    

    addTodo(todo: Todo): Observable<Todo> {
        return this.httpClient.post(`${environment.api}${environment.path}`, JSON.stringify(todo)).pipe(
      catchError((error: any) => Observable.throw(error))
    );
  }
                                   

必须这样使用                                    

    addTodo(todo: Todo): Observable<Todo> {
    return this.httpClient.post<Todo>(`${environment.api}${environment.path}`, JSON.stringify(todo)).pipe(
      catchError((error: any) => Observable.throw(error))
    );
  }
                               

  • 是的,如@ChauTran早在2小时之前回答的那样,但是HttpClient如何与Angular 6而非Angular 5通用,该服务在Angular 5中正常工作? –  Sami-L, 18年5月23日,21:27                                                
  • 呵呵,我想念“ ... post <Todo>”。谢谢! – 卡纳鲁·瓦伦丁 (  Carnaru Valentin)18年7月25日在14:04                                                
添加评论                                

                   


                   

来自  https://stackoverflow.com/questions/50492977/angular-6-rxjs-6-type-observableobject-is-not-assignable-to-type-observabl                    


                   


                   


                       


           



 
活动 2个月前    
观看了 24k次    
14                    

遵循Google在这里发布的Angular 4.3.2官方文档,我能够get从本地json文件发出一个简单的请求。我想练习从JSON占位符站点访问真正的端点,但是我在弄清楚要放在.subscribe()运算符中的内容时遇到了麻烦我创建了一个IUser接口来捕获有效负载的字段,但是带有的行.subscribe(data => {this.users = data})抛出error Type 'Object' is not assignable to type 'IUser[]'处理此问题的正确方法是什么?看起来很基本,但我是菜鸟。                    

我的代码如下:                    

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { IUsers } from './users';

@Component({
  selector: 'pm-http',
  templateUrl: './http.component.html',
  styleUrls: ['./http.component.css']
})
export class HttpComponent implements OnInit {
  productUrl = 'https://jsonplaceholder.typicode.com/users';
  users: IUsers[];
  constructor(private _http: HttpClient) { }

  ngOnInit(): void {    
    this._http.get(this.productUrl).subscribe(data => {this.users = data});
  }

}
               

  • 7                                
    由于数据的类型不是IUsers,请尝试执行以下操作.subscribe((data: IUsers) => ...或 this.users = data as any; – cyr_x 17年  7月31日,23:49                                 
  • 1个                                
    谢谢@cyrix。data as any在我的情况下做到了。 –  negrotico18年 2月26日在22:58                                
添加评论                
       

2个答案                 

正确答案  


               

活跃的最古老的选票                    
       
32                        

您实际上在这里有一些选择,但是可以使用泛型将其转换为所需的类型。                        

   // Notice the Generic of IUsers[] casting the Type for resulting "data"
   this.http.get<IUsers[]>(this.productUrl).subscribe(data => ...

   // or in the subscribe
   .subscribe((data: IUsers[]) => ...
                       

另外,我建议您在模板中使用自动订阅/取消订阅的异步管道,尤其是在您不需要任何花哨的逻辑并且仅映射值的情况下。                        

users: Observable<IUsers[]>; // different type now

this.users = this.http.get<IUsers[]>(this.productUrl);

// template:
*ngFor="let user of users | async"
                   

  • 2                                    
    谢谢,铸造效果很好! – 午夜 17年  8月1日在15:52                                    
添加评论                    
           
       
16                        

我在Angular文档小组工作,一个待办事项是更改这些文档,以显示通过服务访问Http的“最佳实践”方式。                        

这是一个例子:                        

import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/map';

import { IProduct } from './product';

@Injectable()
export class ProductService {
    private _productUrl = './api/products/products.json';

    constructor(private _http: HttpClient) { }

    getProducts(): Observable<IProduct[]> {
        return this._http.get<IProduct[]>(this._productUrl)
            .do(data => console.log('All: ' + JSON.stringify(data)))
            .catch(this.handleError);
    }

    private handleError(err: HttpErrorResponse) {
        // in a real world app, we may send the server to some remote logging infrastructure
        // instead of just logging it to the console
        let errorMessage = '';
        if (err.error instanceof Error) {
            // A client-side or network error occurred. Handle it accordingly.
            errorMessage = `An error occurred: ${err.error.message}`;
        } else {
            // The backend returned an unsuccessful response code.
            // The response body may contain clues as to what went wrong,
            errorMessage = `Server returned code: ${err.status}, error message is: ${err.message}`;
        }
        console.error(errorMessage);
        return Observable.throw(errorMessage);
    }
}
                       

该组件将如下所示:                        

ngOnInit(): void {
    this._productService.getProducts()
            .subscribe(products => this.products = products,
                       error => this.errorMessage = <any>error);
}
                   

  • 刚刚开始您的课程!我将代码重构为服务,以遵循最佳实践! – 午夜 17年  8月1日在15:53                                    
  • 大!仅供参考...该课程当前使用旧的Http服务。我们正在努力进行更新。 – DeborahK 17年  8月1日在16:16                                    
  • 罗杰,我想通过锻炼自己解决这个问题:P – midnightnoir 17年  8月1日在16:51                                    
  • 快速提问,在http.get之后键入api URL的原因是什么?我没有尝试过,它仍然返回正确的数据。 – 午夜 17年  8月1日在16:56                                    
  • 1个                                    
    我也注意到了这一点。我认为这是因为我们定义的函数返回类型。如果我们也删除它,那么数据就是Observable(object)。这样看来,我们可以使用类型转换或方法返回类型。为了清楚起见,我喜欢同时使用两者。 –  DeborahK '17 Aug 8'在17:08                                    
再显示3条评论                    
       

来自  https://stackoverflow.com/questions/45426907/type-object-is-not-assignable-to-type-with-new-httpclient-httpgetmodule            



普通分类: