简体   繁体   English

Observable&lt;{}&gt; 不可分配给 Observable 类型<SomeType[]>

[英]Observable<{}> not assignable to type Observable<SomeType[]>

I'm learning Angular2 and Typescript.我正在学习 Angular2 和 Typescript。 I'm working through the Heroes tutorial on angular.io, but applying it to a project I'm converting from ASP.Net.我正在研究 angular.io 上的 Heroes 教程,但将其应用于我从 ASP.Net 转换的项目。 I've run into a problem which I think is due to my lack of understanding, though as far as I can see it matches what the relevant part of the tutorial is doing.我遇到了一个问题,我认为这是由于我缺乏理解,但据我所知,它与教程的相关部分正在做的事情相匹配。

import { Injectable } from '@angular/core';
import {RiskListSummary} from '../Models/RiskListSummary';
import { Observable } from 'rxjs/Rx';
import { Http, Response } from '@angular/http';

@Injectable()
export class RiskAssessmentListService {

    constructor(private http : Http) {}

    private serviceUrl = "http://myserviceurl/";

    getRisks(): Observable<RiskListSummary[]> {
        return this.http.get(this.serviceUrl)
            .map(this.extractData())
            .catch(this.handleError());
    }

    private extractData(res: Response) {
       if (res.status < 200 || res.status >= 300) {
             throw new Error('Bad response status: ' + res.status);
           }
       let body = res.json();
       return body.data || { };
    }

    private handleError (error: any) {
        let errMsg = error.message || 'Server error';
        console.error(errMsg); // log to console instead
        return Observable.throw(errMsg);
    }
}

I'm getting the following error on the line "return this.http.get(this.serviceUrl)":我在“return this.http.get(this.serviceUrl)”行收到以下错误:

Error:(20, 16) TS2322: Type 'Observable<{}>' is not assignable to type 'Observable'.错误:(20, 16) TS2322:类型“Observable<{}>”不可分配给类型“Observable”。 Type '{}' is not assignable to type 'RiskListSummary[]'.类型“{}”不可分配给类型“RiskListSummary[]”。 Property 'length' is missing in type '{}'.类型“{}”中缺少属性“长度”。

If it makes a difference, I'm using webstorm (latest version), but I think this error is coming straight from the typescript compiler.如果它有所作为,我正在使用 webstorm(最新版本),但我认为这个错误直接来自 typescript 编译器。 I was thinking maybe I need a typings file for rxjs, but the tutorial doesn't use one, and none of the ones that I found with a "typings search" made a difference我在想也许我需要一个 rxjs 的类型文件,但是本教程没有使用一个,而且我通过“类型搜索”找到的文件都没有产生任何影响

The following are my dependencies from package.json:以下是我对 package.json 的依赖:

  "dependencies": {
    "@angular/common":  "2.0.0-rc.1",
    "@angular/compiler":  "2.0.0-rc.1",
    "@angular/core":  "2.0.0-rc.1",
    "@angular/http":  "2.0.0-rc.1",
    "@angular/platform-browser":  "2.0.0-rc.1",
    "@angular/platform-browser-dynamic":  "2.0.0-rc.1",
    "@angular/router":  "2.0.0-rc.1",
    "@angular/router-deprecated":  "2.0.0-rc.1",
    "@angular/upgrade":  "2.0.0-rc.1",

    "systemjs": "0.19.27",
    "es6-shim": "^0.35.0",
    "reflect-metadata": "^0.1.3",
    "rxjs": "5.0.0-beta.6",
    "zone.js": "^0.6.12"

I think that your problem is located here:我认为您的问题出在此处:

getRisks(): Observable<RiskListSummary[]> {
  return this.http.get(this.serviceUrl)
     .map(this.extractData()) <== passing result of function
     .catch(this.handleError()); <== passing result of function
}

You could use just passing function reference:您可以只使用传递function引用:

getRisks(): Observable<RiskListSummary[]> {
  return this.http.get(this.serviceUrl)
     .map(this.extractData)
     .catch(this.handleError);
}

but this way you will lose this .但是这样你就会失去this

Or you could use bind method to retain this :或者你可以使用bind方法来保留this

getRisks(): Observable<RiskListSummary[]> {
  return this.http.get(this.serviceUrl)
    .map(this.extractData.bind(this))
    .catch(this.handleError.bind(this));
}

however you will lose type checking .但是你会失去类型检查

I would leverage arrow functions to be able to use lexical this :我会利用箭头函数来使用词法 this

getRisks(): Observable<RiskListSummary[]> {
  return this.http.get(this.serviceUrl)
    .map(res => this.extractData(res))
    .catch(err => this.handleError(err));
}

Without it, the this variable will point to the function where the call is made, instead of the instance that contains getRisks() .没有它, this变量将指向进行调用的函数,而不是包含getRisks()的实例。

I had same problem, however no matter how I changed as above mentioned,It still not working.我有同样的问题,但是无论我如何改变如上所述,它仍然无法正常工作。 Until my college found this map, catch defination as VSC prompted直到我的大学找到这张地图,按照 VSC 的提示捕捉定义

so the proper change should be like (add type cast the following place)所以正确的改变应该是(在下面的地方添加类型转换)

getRisks(): Observable<RiskListSummary[]> {
  return this.http.get(this.serviceUrl)
    .map<RiskListSummary[]>(this.extractData)
    .catch<RiskListSummary[]>(this.handleError);
}

I am new to TypeScript.我是 TypeScript 的新手。 so this kind of [method signature] really give me a hammer on the head :(所以这种[方法签名]真的给了我一个锤子:(

But finally it worked out :)但最后它解决了:)

According to the getRisks() fn, you are types to return Observable<RiskListSummary[]> .根据getRisks() fn,您是返回Observable<RiskListSummary[]>的类型。 However in your code, you are returning body.data || {}但是在您的代码中,您正在返回body.data || {} body.data || {} . body.data || {} I believe you need to interface your RiskListSummary[] to your body.data.我相信您需要将您的 RiskListSummary[] 连接到您的 body.data。

I found the next: AccessTokens was missing.我找到了下一个:缺少 AccessTokens。 So,i made the change and it workted: On your model (in my case Country) edit de file and change from:因此,我进行了更改并且它起作用了:在您的模型(在我的情况下为国家/地区)上编辑 de 文件并从以下位置更改:

export interface CountryInterface {
  "id"?: any;
  "name": string;
  "order"?: number;  
}

export class Country implements CountryInterface {
  "id": any;
  "name": string;
  "order": number;
   ....
}

To:至:

export interface CountryInterface {
  "id"?: any;
  "name": string;
  "order"?: number;
  accessTokens: any[];
}

export class Country implements CountryInterface {
  "id": any;
  "name": string;
  "order": number;
  accessTokens: any[];
  ...
}

I have similar issue while working on my side project, the problem here is the interface in the function that is managing the returning value es extractData() you can give it an explicit interface which then correct the type of value you are managing.我在处理我的副项目时遇到了类似的问题,这里的问题是管理返回值es extractData()的函数中的接口,你可以给它一个显式接口,然后更正你正在管理的值的类型。

example例子

private extractData(res: {status: number}) {
   if (res.status < 200 || res.status >= 300) {
         throw new Error('Bad response status: ' + res.status);
       }
   let body = res.json();
   return body.data || { };
}

and then the status type will be set to type on a compilation run time.然后状态类型将设置为编译运行时的类型。

Thank you Lamin-jr谢谢Lamin-jr

Typescript是一个编译器工具,它总是会给出类型检查编译错误,因为在这种情况下getRisk方法应该指定它返回类型为RiskListSummary的Observable,这样工具应该识别出这个方法的预期并检查类型在订阅方法中使用时的安全性。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 'Observable' 不可分配给类型 'EffectResult' - 'Observable' is not assignable to type 'EffectResult' 输入“可观察的<documentdata[]> ' 不可赋值</documentdata[]> - Type 'Observable<DocumentData[]>' is not assignable 输入 &#39;() =&gt; Observable<any> &#39; 不可分配给类型 &#39;() =&gt; Observable<any> &#39; - Type '() => Observable<any>' is not assignable to type '() => Observable<any>' 类型&#39;Observable &lt;{}不可分配给类型&#39;Observable <HttpEvent<any> &gt;” - Type 'Observable<{} is not assignable to type 'Observable<HttpEvent<any>>' Typescript:类型“ Observable &lt;{}&gt;”不可分配给类型“ Observable” - Typescript : Type 'Observable<{}>' is not assignable to type 'Observable' 键入&#39;Observable &lt;{} | 无法将用户&gt;分配给类型“可观察” <User> “ - Type 'Observable<{} | User>' is not assignable to type 'Observable<User>' 类型“可观察” <any> &#39;不可分配给&#39;Observable类型 <T> &#39; - Type 'Observable<any>' is not assignable to type 'Observable<T>' 类型&#39;可观察的<ArrayBuffer> &#39; 不可分配给类型 &#39;Observable<Date[]> &#39; - Type 'Observable<ArrayBuffer>' is not assignable to type 'Observable<Date[]>' 类型'可观察的<httpevent<> &gt;' 不可分配给类型 'Observable&lt;&gt;' </httpevent<> - Type 'Observable<HttpEvent<>>' is not assignable to type 'Observable<>' 类型“ Observable &lt;{} []&gt;”不可分配给类型“ Observable” <RequestOffer[]> &#39; - Type 'Observable<{}[]>' is not assignable to type 'Observable<RequestOffer[]>'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM