0
我對使用Angular 2的Observable和我的結構不會收到結果是新手,即使我可以驗證來自我的REST API的響應。類型'Observable <any>'不可分配以鍵入'StoresSummaryResults'。屬性「數據」缺少類型'Observable <any>'
我在Typescript中有以下數據類。
import { RESTResult } from '../common/RESTResult'; // Common Response Structure
import { StoresSummaryData } from './StoresSummaryData'; // Structure of records being returned as an array
export class StoresSummaryResults extends RESTResult {
Data: Array<StoresSummaryData>; // Data[] is array ofStoresSummaryData structure ({ field1, field2 ...)
constructor() {
super();
this.Data = new Array<StoresSummaryData>(); // Ensure 1 records exists for testing
this.Data.push(new StoresSummaryData(0, 0));
}
}
結果從REST API檢索
getResults(): Observable<StoresSummaryResults> { // Structure
return this.http.get(this.RequestHttpPath)
.map(this.extractData)
.catch(this.handleError);
};
private extractData(res: Response) {
let body = res.json();
return body.data || {};
}
StoreInfo: StoresSummaryResults;
public constructor(private storesService: StoresService) { }
showResults(): void {
this.StoreInfo = this.storesService.getResults();
}
我得到的錯誤:
Typescript Error
Type 'Observable<StoresSummaryResults>' is not assignable to type 'StoresSummaryResults'. Property 'Data' is missing in type 'Observable<StoresSummaryResults>'.
我有,雖然定義的數據結構,所以我不知道該怎麼正確。
感謝您的快速回復。這糾正了我的錯誤。在較早的測試代碼中,我使用了Observable的定義,但剛剛在代碼的另一部分收到了錯誤。我試圖在沒有HTTP調用的情況下驗證我的代碼。在試圖簡單地返回'Result = new Observable ()'我不能將項目添加到StoreInfo結構。我不知道如何通過添加結構來輕鬆測試。 –
你當然可以這樣做,但是你想要在'subscribe()'中構造包含'StoreInfo'屬性的任何類(你沒有包括定義)。這樣,班級本身不必等待結果。或者你可以通過模擬'storeService'返回'Observable.return(storeInfoValue)'來測試它。 –