我正在學習Angular2和Typescript。我正在研究angular.io上的英雄教程,但將其應用到我從ASP.Net轉換而來的項目中。我遇到了一個我認爲是因爲我缺乏理解的問題,但據我所知,它與本教程的相關部分相匹配。可觀察<{}>不可分配到類型可觀察<SomeType[]>
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);
}
}
我收到以下錯誤就行了 「迴歸this.http.get(this.serviceUrl)」:
Error:(20, 16) TS2322: Type 'Observable<{}>' is not assignable to type 'Observable'. Type '{}' is not assignable to type 'RiskListSummary[]'. Property 'length' is missing in type '{}'.
如果它的確與衆不同,我使用webstorm(最新版本),但我認爲這個錯誤直接來自打字稿編譯器。我在想也許我需要一個rxjs的打字文件,但教程不使用一個,而我發現的「打字搜索」中找不到的打了個差別
以下是我對軟件包的依賴關係。 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"
謝謝,這個技巧就是這樣做的,我假設在原始示例中有.Net的擴展方法在工作(https: //angular.io/docs/ts/latest/guide/server-communication.html#)我想我需要開始一個新的項目,看看他們的例子是否仍然給出相同的錯誤 –